]> git.uio.no Git - u/mrichter/AliRoot.git/blob - HLT/trigger/AliHLTGlobalTriggerComponent.cxx
Update of the SSD on-line clusterfinder:
[u/mrichter/AliRoot.git] / HLT / trigger / AliHLTGlobalTriggerComponent.cxx
1 // $Id$
2 /**************************************************************************
3  * This file is property of and copyright by the ALICE HLT Project        *
4  * ALICE Experiment at CERN, All rights reserved.                         *
5  *                                                                        *
6  * Primary Authors: Artur Szostak <artursz@iafrica.com>                   *
7  *                  for The ALICE HLT Project.                            *
8  *                                                                        *
9  * Permission to use, copy, modify and distribute this software and its   *
10  * documentation strictly for non-commercial purposes is hereby granted   *
11  * without fee, provided that the above copyright notice appears in all   *
12  * copies and that both the copyright notice and this permission notice   *
13  * appear in the supporting documentation. The authors make no claims     *
14  * about the suitability of this software for any purpose. It is          *
15  * provided "as is" without express or implied warranty.                  *
16  **************************************************************************/
17
18 /// @file   AliHLTGlobalTriggerComponent.cxx
19 /// @author Artur Szostak <artursz@iafrica.com>
20 /// @date   26 Nov 2008
21 /// @brief  Implementation of the AliHLTGlobalTriggerComponent component class.
22 ///
23 /// The AliHLTGlobalTriggerComponentComponent class applies the global HLT trigger to all
24 /// trigger information produced by components deriving from AliHLTTrigger.
25
26 #include "AliHLTGlobalTriggerComponent.h"
27 #include "AliHLTGlobalTriggerDecision.h"
28 #include "AliHLTGlobalTrigger.h"
29 #include "AliHLTGlobalTriggerConfig.h"
30 #include "AliHLTTriggerMenu.h"
31 #include "AliHLTCTPData.h"
32 #include "AliCDBManager.h"
33 #include "AliCDBStorage.h"
34 #include "AliCDBEntry.h"
35 #include "TUUID.h"
36 #include "TROOT.h"
37 #include "TSystem.h"
38 #include "TRegexp.h"
39 #include "TClonesArray.h"
40 #include "TObjString.h"
41 #include "TString.h"
42 #include "TInterpreter.h"
43 #include "TDatime.h"
44 #include "TClass.h"
45 #include "TNamed.h"
46 #include <fstream>
47 #include <cerrno>
48 #include <cassert>
49 #include <vector>
50 #include <algorithm>
51
52 ClassImp(AliHLTGlobalTriggerComponent)
53
54 const char* AliHLTGlobalTriggerComponent::fgkTriggerMenuCDBPath = "HLT/ConfigHLT/HLTGlobalTrigger";
55
56
57 namespace
58 {
59   /**
60    * This method is used as a comparison functor with the STL sort routines.
61    */
62   bool AliHLTDescendingNumbers(UInt_t a, UInt_t b)
63   {
64     return a > b;
65   }
66 } // end of namespace
67
68
69 AliHLTGlobalTriggerComponent::AliHLTGlobalTriggerComponent() :
70         AliHLTTrigger(),
71         fTrigger(NULL),
72         fDebugMode(false),
73         fRuntimeCompile(true),
74         fDeleteCodeFile(false),
75         fCodeFileName(),
76         fClassName(),
77         fCTPDecisions(NULL),
78         fBufferSizeConst(2*(sizeof(AliHLTGlobalTriggerDecision) + sizeof(AliHLTReadoutList))),
79         fBufferSizeMultiplier(1.),
80         fIncludePaths(TObjString::Class()),
81         fIncludeFiles(TObjString::Class()),
82         fLibStateAtLoad(),
83         fBits(0),
84         fDataEventsOnly(true)
85 {
86   // Default constructor.
87   
88   ClearInfoForNewEvent(false);
89 }
90
91
92 AliHLTGlobalTriggerComponent::~AliHLTGlobalTriggerComponent()
93 {
94   // Default destructor.
95   
96   if (fTrigger != NULL) delete fTrigger;
97
98   if (fCTPDecisions) {
99     fCTPDecisions->Delete();
100     delete fCTPDecisions;
101   }
102 }
103
104
105 void AliHLTGlobalTriggerComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& list) const
106 {
107   // Returns the kAliHLTDataTypeGlobalTrigger type as output.
108   list.push_back(kAliHLTDataTypeGlobalTrigger);
109 }
110
111
112 void AliHLTGlobalTriggerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
113 {
114   // Returns the output data size estimate.
115
116   constBase = fBufferSizeConst;
117   inputMultiplier = fBufferSizeMultiplier;
118 }
119
120
121 Int_t AliHLTGlobalTriggerComponent::DoInit(int argc, const char** argv)
122 {
123   // Initialises the global trigger component.
124   
125   fDebugMode = false;
126   fClassName = "";
127   fCodeFileName = "";
128   fDeleteCodeFile = false;
129   const char* configFileName = NULL;
130   const char* codeFileName = NULL;
131   fIncludePaths.Clear();
132   fIncludeFiles.Clear();
133   SetBit(kIncludeInput);
134   fDataEventsOnly = true;
135   
136   for (int i = 0; i < argc; i++)
137   {
138     if (strcmp(argv[i], "-config") == 0)
139     {
140       if (configFileName != NULL)
141       {
142         HLTWarning("Trigger configuration macro was already specified."
143                    " Will replace previous value given by -config."
144         );
145       }
146       if (argc <= i+1)
147       {
148         HLTError("The trigger configuration macro filename was not specified." );
149         return -EINVAL;
150       }
151       configFileName = argv[i+1];
152       i++;
153       continue;
154     }
155     
156     if (strcmp(argv[i], "-includepath") == 0)
157     {
158       if (argc <= i+1)
159       {
160         HLTError("The include path was not specified." );
161         return -EINVAL;
162       }
163       try
164       {
165         new (fIncludePaths[fIncludePaths.GetEntriesFast()]) TObjString(argv[i+1]);
166       }
167       catch (const std::bad_alloc&)
168       {
169         HLTError("Could not allocate more memory for the fIncludePaths array.");
170         return -ENOMEM;
171       }
172       i++;
173       continue;
174     }
175     
176     if (strcmp(argv[i], "-include") == 0)
177     {
178       if (argc <= i+1)
179       {
180         HLTError("The include file name was not specified." );
181         return -EINVAL;
182       }
183       try
184       {
185         new (fIncludeFiles[fIncludeFiles.GetEntriesFast()]) TObjString(argv[i+1]);
186       }
187       catch (const std::bad_alloc&)
188       {
189         HLTError("Could not allocate more memory for the fIncludeFiles array.");
190         return -ENOMEM;
191       }
192       i++;
193       continue;
194     }
195     
196     if (strcmp(argv[i], "-debug") == 0)
197     {
198       if (fDebugMode == true)
199       {
200         HLTWarning("The debug flag was already specified. Ignoring this instance.");
201       }
202       fDebugMode = true;
203       continue;
204     }
205     
206     if (strcmp(argv[i], "-cint") == 0)
207     {
208       fRuntimeCompile = false;
209       continue;
210     }
211     
212     if (strcmp(argv[i], "-usecode") == 0)
213     {
214       if (codeFileName != NULL)
215       {
216         HLTWarning("Custom trigger code file was already specified."
217                    " Will replace previous value given by -usecode."
218         );
219       }
220       if (argc <= i+1)
221       {
222         HLTError("The custom trigger code filename was not specified." );
223         return -EINVAL;
224       }
225       codeFileName = argv[i+1];
226       if (argc <= i+2)
227       {
228         HLTError("The custom trigger class name was not specified." );
229         return -EINVAL;
230       }
231       fClassName = argv[i+2];
232       i += 2;
233       continue;
234     }
235
236     if (strcmp(argv[i], "-skipctp") == 0)
237     {
238       HLTInfo("Skipping CTP counters in trigger decision");
239       SetBit(kSkipCTP);
240       continue;
241     }
242
243     if (strcmp(argv[i], "-forward-input") == 0)
244     {
245       HLTInfo("Forwarding input objects and trigger decisions");
246       SetBit(kForwardInput);
247       SetBit(kIncludeShort);
248       SetBit(kIncludeInput, false);
249       continue;
250     }
251
252     if (strstr(argv[i], "-include-input") == argv[i])
253     {
254       SetBit(kForwardInput,false);
255       TString param=argv[i];
256       param.ReplaceAll("-include-input", "");
257       if (param.CompareTo("=none")==0) 
258       {
259         HLTInfo("skipping objects and trigger decisions");
260         SetBit(kIncludeShort, false);
261         SetBit(kIncludeInput, false);
262       }
263       else if (param.CompareTo("=short")==0) 
264       {
265         HLTInfo("including short info on objects and trigger decisions");
266         SetBit(kIncludeShort);
267         SetBit(kIncludeInput, false);
268       }
269       else if (param.CompareTo("=both")==0) 
270       {
271         HLTInfo("including input objects, trigger decisions and short info");
272         SetBit(kIncludeShort);
273         SetBit(kIncludeInput);
274       }
275       else if (param.CompareTo("=objects")==0 || param.IsNull())
276       {
277         HLTInfo("including input objects and trigger decisions");
278         SetBit(kIncludeShort, false);
279         SetBit(kIncludeInput);
280       }
281       else
282       {
283         HLTError("unknown parameter '%s' for argument '-include-input'", param.Data());
284       }
285       continue;
286     }
287
288     if (strcmp(argv[i], "-process-all-events") == 0)
289     {
290       fDataEventsOnly = false;
291       continue;
292     }
293     
294     HLTError("Unknown option '%s'.", argv[i]);
295     return -EINVAL;
296   } // for loop
297   
298   const AliHLTTriggerMenu* menu = NULL;
299   if (configFileName != NULL)
300   {
301     TString cmd = ".x ";
302     cmd += configFileName;
303     gROOT->ProcessLine(cmd);
304     menu = AliHLTGlobalTriggerConfig::Menu();
305   }
306   
307   // Try load the trigger menu from the CDB if it is not loaded yet with the
308   // -config option
309   int result = -ENOENT;
310   if (menu == NULL)
311   {
312     result = LoadTriggerMenu(fgkTriggerMenuCDBPath, menu);
313   }
314   if (menu == NULL)
315   {
316     HLTError("No trigger menu configuration found or specified.");
317     return result;
318   }
319   
320   if (codeFileName == NULL)
321   {
322     result = GenerateTrigger(menu, fClassName, fCodeFileName, fIncludePaths, fIncludeFiles);
323     if (result == 0) fDeleteCodeFile = true;
324   }
325   else
326   {
327     result = LoadTriggerClass(codeFileName, fIncludePaths);
328     if (result == 0) fCodeFileName = codeFileName;
329   }
330   if (result != 0) return result;
331   
332   try
333   {
334     fTrigger = AliHLTGlobalTrigger::CreateNew(fClassName.Data());
335   }
336   catch (const std::bad_alloc&)
337   {
338     HLTError("Could not allocate memory for the AliHLTGlobalTrigger instance.");
339     return -ENOMEM;
340   }
341   if (fTrigger == NULL)
342   {
343     HLTError("Could not create a new instance of '%s'.", fClassName.Data());
344     return -EIO;
345   }
346   
347   fTrigger->FillFromMenu(*menu);
348   if (fTrigger->CallFailed()) return -EPROTO;
349
350   // setup the CTP accounting in AliHLTComponent
351   SetupCTPData();
352
353   // Set the default values from the trigger menu.
354   SetDescription(menu->DefaultDescription());
355   SetTriggerDomain(menu->DefaultTriggerDomain());
356   
357   return 0;
358 }
359
360
361 Int_t AliHLTGlobalTriggerComponent::DoDeinit()
362 {
363   // Cleans up the global trigger component.
364   
365   if (fTrigger != NULL)
366   {
367     delete fTrigger;
368     fTrigger = NULL;
369   }
370   
371   if (fCTPDecisions) {
372     fCTPDecisions->Delete();
373     delete fCTPDecisions;
374   }
375   fCTPDecisions=NULL;
376   
377   Int_t result = UnloadTriggerClass(fCodeFileName);
378   if (result != 0) return result;
379   
380   if (fDeleteCodeFile and !fCodeFileName.IsNull() && gSystem->AccessPathName(fCodeFileName)==0 && !fDebugMode) {
381     fCodeFileName.ReplaceAll(".cxx", "*");
382     TString command="rm "; command+=fCodeFileName;
383     gSystem->Exec(command);
384   }
385   fCodeFileName="";
386   fDeleteCodeFile=false;
387
388   return 0;
389 }
390
391
392 AliHLTComponent* AliHLTGlobalTriggerComponent::Spawn()
393 {
394   // Creates a new object instance.
395   AliHLTComponent* comp = NULL;
396   try
397   {
398     comp = new AliHLTGlobalTriggerComponent;
399   }
400   catch (const std::bad_alloc&)
401   {
402     HLTError("Could not allocate memory for a new instance of AliHLTGlobalTriggerComponent.");
403     return NULL;
404   }
405   return comp;
406 }
407
408
409 int AliHLTGlobalTriggerComponent::DoTrigger()
410 {
411   // This method will apply the global trigger decision.
412
413   if (fTrigger == NULL)
414   {
415     HLTFatal("Global trigger implementation object is NULL!");
416     return -EIO;
417   }
418
419   AliHLTUInt32_t eventType=0;
420   if (!IsDataEvent(&eventType)) {
421     if (eventType==gkAliEventTypeEndOfRun) PrintStatistics(fTrigger, kHLTLogImportant, 0);
422     if (fDataEventsOnly)
423     {
424       IgnoreEvent();
425       return 0;
426     }
427   }
428
429   // Copy the trigger counters in case we need to set them back to their original
430   // value because the PushBack method fails with ENOSPC.
431   TArrayL64 originalCounters = fTrigger->GetCounters();
432   if (fTrigger->CallFailed()) return -EPROTO;
433   
434   fTrigger->NewEvent();
435   if (fTrigger->CallFailed()) return -EPROTO;
436   
437   // Fill in the input data.
438   const TObject* obj = GetFirstInputObject();
439   while (obj != NULL)
440   {
441     fTrigger->Add(obj, GetDataType(), GetSpecification());
442     if (fTrigger->CallFailed()) return -EPROTO;
443     obj = GetNextInputObject();
444   }
445
446   // add trigger decisions for every CTP class
447   const AliHLTCTPData* pCTPData=CTPData();
448   if (pCTPData) {
449     AddCTPDecisions(fTrigger, pCTPData, GetTriggerData());
450   }
451
452   // Calculate the global trigger result and trigger domain, then create and push
453   // back the new global trigger decision object.
454   TString description;
455   AliHLTTriggerDomain triggerDomain;
456   bool triggerResult = fTrigger->CalculateTriggerDecision(triggerDomain, description);
457   if (fTrigger->CallFailed()) return -EPROTO;
458   AliHLTGlobalTriggerDecision decision(
459       triggerResult,
460       // The following will cause the decision to be generated with default values
461       // (set in fTriggerDomain and fDescription) if the trigger result is false.
462       (triggerResult == true) ? triggerDomain : GetTriggerDomain(),
463       (triggerResult == true) ? description.Data() : GetDescription()
464     );
465
466   // mask the readout list according to the CTP trigger
467   // if the classes have been initialized (mask non-zero)
468   if (pCTPData && pCTPData->Mask()) {
469     AliHLTEventDDL eventDDL=pCTPData->ReadoutList(*GetTriggerData());
470     AliHLTReadoutList ctpreadout(eventDDL);
471     ctpreadout.Enable(AliHLTReadoutList::kHLT);
472     AliHLTReadoutList maskedList=decision.ReadoutList();
473     maskedList.AndEq(ctpreadout);
474     decision.ReadoutList(maskedList);
475   }
476
477   decision.SetCounters(fTrigger->GetCounters(), GetEventCount()+1);
478   if (fTrigger->CallFailed()) return -EPROTO;
479   
480   static UInt_t lastTime=0;
481   TDatime time;
482   if (time.Get()-lastTime>60) {
483     lastTime=time.Get();
484     PrintStatistics(fTrigger, kHLTLogImportant);
485   }
486   
487   // Add the input objects used to the global decision.
488   TClonesArray* pShortInfo=NULL;
489   if (TestBit(kIncludeShort)) {
490     try
491     {
492       pShortInfo=new TClonesArray(TNamed::Class(), GetNumberOfInputBlocks());
493     }
494     catch (const std::bad_alloc&)
495     {
496       HLTError("Could not allocate memory for a short list of input objects.");
497       delete pShortInfo;
498       return -ENOMEM;
499     }
500   }
501   obj = GetFirstInputObject();
502   while (obj != NULL)
503   {
504     if (TestBit(kForwardInput)) {
505       Forward(obj);
506     }
507     if (TestBit(kIncludeInput)) {
508     if (obj->IsA() == AliHLTTriggerDecision::Class())
509     {
510       decision.AddTriggerInput( *static_cast<const AliHLTTriggerDecision*>(obj) );
511     }
512     else
513     {
514       decision.AddInputObject(obj);
515     }
516     }
517
518     if (TestBit(kIncludeShort)) {
519       int entries=pShortInfo->GetEntriesFast();
520       try
521       {
522         new ((*pShortInfo)[entries]) TNamed(obj->GetName(), obj->GetTitle());
523       }
524       catch (const std::bad_alloc&)
525       {
526         HLTError("Could not allocate more memory for the short list of input objects.");
527         delete pShortInfo;
528         return -ENOMEM;
529       }
530       if (obj->IsA() == AliHLTTriggerDecision::Class()) {
531         (*pShortInfo)[entries]->SetBit(BIT(16)); // indicate that this is a trigger decision
532         (*pShortInfo)[entries]->SetBit(BIT(15), ((AliHLTTriggerDecision*)obj)->Result());
533       }
534     }
535
536     obj = GetNextInputObject();
537   }
538   if (pShortInfo) {
539     decision.AddInputObject(pShortInfo);
540     pShortInfo->Delete();
541     delete pShortInfo;
542     pShortInfo=NULL;
543   }
544
545   if (!TestBit(kSkipCTP) && CTPData()) decision.AddInputObject(CTPData());
546
547   // add readout filter to event done data
548   CreateEventDoneReadoutFilter(decision.TriggerDomain(), 3);
549   // add monitoring filter to event done data
550   CreateEventDoneReadoutFilter(decision.TriggerDomain(), 4);
551   if (decision.Result()) {
552     // add monitoring event command for triggered events
553     CreateEventDoneReadoutFilter(decision.TriggerDomain(), 5);
554   }
555   if (TriggerEvent(&decision) == -ENOSPC)
556   {
557     // Increase the estimated buffer space required if the PushBack methods in TriggerEvent
558     // returned the "no buffer space" error code. Also remember to set the trigger counters
559     // back to what they were, otherwise triggers will be double counted when we try to reprocess
560     // this event with larger buffers.
561     fBufferSizeConst += 1024*1024;
562     fBufferSizeMultiplier *= 2.;
563     fTrigger->SetCounters(originalCounters);
564     if (fTrigger->CallFailed()) return -EPROTO;
565     return -ENOSPC;
566   }
567   return 0;
568 }
569
570
571 int AliHLTGlobalTriggerComponent::Reconfigure(const char* cdbEntry, const char* chainId)
572 {
573   // Reconfigure the component by loading the trigger menu and recreating the
574   // trigger logic class.
575   
576   const char* path = fgkTriggerMenuCDBPath;
577   const char* id = "(unknown)";
578   if (cdbEntry != NULL) path = cdbEntry;
579   if (chainId != NULL and chainId[0] != '\0') id = chainId;
580   HLTInfo("Reconfiguring from '%s' for chain component '%s'.", path, id);
581   
582   const AliHLTTriggerMenu* menu = NULL;
583   int result = LoadTriggerMenu(path, menu);
584   if (result != 0) return result;
585   
586   TString className;
587   TString codeFileName;
588   result = GenerateTrigger(menu, className, codeFileName, fIncludePaths, fIncludeFiles);
589   if (result != 0) return result;
590   
591   AliHLTGlobalTrigger* trigger = NULL;
592   try
593   {
594     trigger = AliHLTGlobalTrigger::CreateNew(className.Data());
595   }
596   catch (const std::bad_alloc&)
597   {
598     HLTError("Could not allocate memory for the AliHLTGlobalTrigger instance.");
599     return -ENOMEM;
600   }
601   if (trigger == NULL)
602   {
603     HLTError("Could not create a new instance of '%s'.", className.Data());
604     // Make sure to cleanup after the new code file.
605     UnloadTriggerClass(codeFileName);
606     if (not codeFileName.IsNull() and gSystem->AccessPathName(codeFileName)==0 and not fDebugMode)
607     {
608       codeFileName.ReplaceAll(".cxx", "*");
609       TString command="rm "; command+=codeFileName;
610       gSystem->Exec(command);
611     }
612     return -EIO;
613   }
614   
615   if (fTrigger != NULL)
616   {
617     delete fTrigger;
618     fTrigger = NULL;
619   }
620   
621   fTrigger = trigger;
622   fTrigger->FillFromMenu(*menu);
623   if (fTrigger->CallFailed()) return -EPROTO;
624
625   // Set the default values from the trigger menu.
626   SetDescription(menu->DefaultDescription());
627   SetTriggerDomain(menu->DefaultTriggerDomain());
628   
629   // Cleanup the old class code.
630   UnloadTriggerClass(fCodeFileName);
631   if (fDeleteCodeFile and not fCodeFileName.IsNull() and gSystem->AccessPathName(fCodeFileName)==0 and not fDebugMode)
632   {
633     fCodeFileName.ReplaceAll(".cxx", "*");
634     TString command="rm "; command+=fCodeFileName;
635     gSystem->Exec(command);
636   }
637   fCodeFileName = codeFileName;
638   fDeleteCodeFile = true;  // Since we generated a new class.
639   
640   return 0;
641 }
642
643
644 int AliHLTGlobalTriggerComponent::LoadTriggerMenu(const char* cdbPath, const AliHLTTriggerMenu*& menu)
645 {
646   // Loads the trigger menu object from the CDB path.
647   
648   HLTDebug("Trying to load trigger menu from '%s'.", cdbPath);
649   if (AliCDBManager::Instance() == NULL)
650   {
651     HLTError("CDB manager object not found.");
652     return -EIO;
653   }
654   AliCDBStorage* store = AliCDBManager::Instance()->GetDefaultStorage();
655   if (store == NULL)
656   {
657     HLTError("Could not get the the default storage for the CDB.");
658     return -EIO;
659   }
660   Int_t version = store->GetLatestVersion(cdbPath, GetRunNo());
661   Int_t subVersion = store->GetLatestSubVersion(cdbPath, GetRunNo(), version);
662   AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, GetRunNo(), version, subVersion);
663   if (entry == NULL)
664   {
665     HLTError("Could not get the CDB entry for \"%s\".", cdbPath);
666     return -EIO;
667   }
668   TObject* obj = entry->GetObject();
669   if (obj == NULL)
670   {
671     HLTError("Configuration object for \"%s\" is missing.", cdbPath);
672     return -ENOENT;
673   }
674   if (obj->IsA() != AliHLTTriggerMenu::Class())
675   {
676     HLTError("Wrong type for configuration object in \"%s\". Found a %s but we expect a AliHLTTriggerMenu.",
677              cdbPath, obj->ClassName()
678     );
679     return -EPROTO;
680   }
681   menu = static_cast<AliHLTTriggerMenu*>(obj);
682   return 0;
683 }
684
685
686 int AliHLTGlobalTriggerComponent::GenerateTrigger(
687     const AliHLTTriggerMenu* menu, TString& name, TString& filename,
688     const TClonesArray& includePaths, const TClonesArray& includeFiles
689   )
690 {
691   // Generates the global trigger class that will implement the specified trigger menu.
692   // See header for more details.
693   
694   HLTDebug("Generating custom HLT trigger class named %s using trigger menu %p.", ((void*)menu), name.Data());
695   
696   // Create a new UUID and replace the '-' characters with '_' to make it a valid
697   // C++ symbol name.
698   TUUID uuid;
699   TString uuidstr = uuid.AsString();
700   for (Int_t i = 0; i < uuidstr.Length(); i++)
701   {
702     if (uuidstr[i] == '-') uuidstr[i] = '_';
703   }
704   
705   // Create the name of the new class.
706   name = "AliHLTGlobalTriggerImpl_";
707   name += uuidstr;
708   filename = name + ".cxx";
709   
710   // Open a text file to write the code and generate the new class.
711   fstream code(filename.Data(), ios_base::out | ios_base::trunc);
712   if (not code.good())
713   {
714     HLTError("Could not open file '%s' for writing.", filename.Data());
715     return -EIO;
716   }
717   
718   TClonesArray symbols(AliHLTTriggerMenuSymbol::Class());
719   int result = BuildSymbolList(menu, symbols);
720   if (result != 0) return result;
721   
722   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
723   code << "#include <cstring>" << endl;
724   code << "#include \"TString.h\"" << endl;
725   code << "#include \"TClonesArray.h\"" << endl;
726   code << "#include \"AliHLTLogging.h\"" << endl;
727   code << "#include \"AliHLTGlobalTrigger.h\"" << endl;
728   code << "#include \"AliHLTGlobalTriggerDecision.h\"" << endl;
729   code << "#include \"AliHLTDomainEntry.h\"" << endl;
730   code << "#include \"AliHLTTriggerDomain.h\"" << endl;
731   code << "#include \"AliHLTReadoutList.h\"" << endl;
732   code << "#include \"AliHLTTriggerMenu.h\"" << endl;
733   code << "#include \"AliHLTTriggerMenuItem.h\"" << endl;
734   code << "#include \"AliHLTTriggerMenuSymbol.h\"" << endl;
735   
736   // Add any include files that were specified on the command line.
737   for (Int_t i = 0; i < includeFiles.GetEntriesFast(); i++)
738   {
739     TString file = static_cast<TObjString*>(includeFiles.UncheckedAt(i))->String();
740     code << "#include \"" << file.Data() << "\"" << endl;
741   }
742   
743   if (fDebugMode)
744   {
745     code << "#else" << endl;
746     code << "const char* gFunctionName = \"???\";" << endl;
747     code << "#define HLTDebug(msg) if (CheckFilter(kHLTLogDebug) && CheckGroup(Class_Name())) SendMessage(kHLTLogDebug, Class_Name(), ::gFunctionName, __FILE__, __LINE__, msg)" << endl;
748   }
749   code << "#endif" << endl;
750   
751   code << "class " << name << " :" << endl;
752   // Add appropriate #ifdef sections since we need to prevent inheritance from
753   // AliHLTGlobalTrigger. CINT does not seem to support multiple inheritance nor
754   // multiple levels of inheritance. Neither of the following schemes worked:
755   //
756   // 1)  class AliHLTGlobalTrigger : public AliHLTLogging {};
757   //     class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger {};
758   //
759   // 2)  class AliHLTGlobalTrigger {};
760   //     class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger, public AliHLTLogging {};
761   //
762   // Thus, we are forced to just inherit from AliHLTLogging when running in the CINT
763   // interpreter. But we anyway have to call the global trigger implementation class
764   // through the AliHLTGlobalTriggerWrapper so this is not such a problem.
765   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
766   code << "  public AliHLTGlobalTrigger," << endl;
767   code << "#endif" << endl;
768   code << "  public AliHLTLogging" << endl;
769   code << "{" << endl;
770   code << "public:" << endl;
771   
772   // Generate constructor method.
773   code << "  " << name << "() :" << endl;
774   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
775   code << "    AliHLTGlobalTrigger()," << endl;
776   code << "#endif" << endl;
777   code << "    AliHLTLogging()";
778   // Write the symbols in the trigger menu in the initialisation list.
779   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
780   {
781     code << "," << endl;
782     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
783     code << "    " << symbol->Name() << "()," << endl;
784     if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
785     {
786       code << "    " << symbol->Name() << "TriggerDomain()," << endl;
787     }
788     code << "    " << symbol->Name() << "DomainEntry(kAliHLTAnyDataType)";
789   }
790   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
791   {
792     code << "," << endl << "    fMenuItemDescription" << i << "()";
793   }
794   code << endl << "  {" << endl;
795   if (fDebugMode)
796   {
797     code << "#ifdef __CINT__" << endl;
798     code << "    gFunctionName = \"" << name.Data() <<"\";" << endl;
799     code << "#endif" << endl;
800     code << "    SetLocalLoggingLevel(kHLTLogAll);" << endl;
801     code << "    HLTDebug(Form(\"Creating new instance at %p.\", this));" << endl;
802   }
803   code << "  }" << endl;
804   
805   code << "  virtual ~" << name << "() {" << endl;
806   if (fDebugMode)
807   {
808     code << "#ifdef __CINT__" << endl;
809     code << "    gFunctionName = \"~" << name.Data() << "\";" << endl;
810     code << "#endif" << endl;
811     code << "    HLTDebug(Form(\"Deleting instance at %p.\", this));" << endl;
812   }
813   code << "  }" << endl;
814   
815   // Generate the FillFromMenu method.
816   code << "  virtual void FillFromMenu(const AliHLTTriggerMenu& menu) {" << endl;
817   if (fDebugMode)
818   {
819     code << "#ifdef __CINT__" << endl;
820     code << "    gFunctionName = \"FillFromMenu\";" << endl;
821     code << "#endif" << endl;
822     code << "    HLTDebug(Form(\"Filling description entries from trigger menu for global trigger %p.\", this));" << endl;
823   }
824   code << "    fCounter.Set(menu.NumberOfItems());" << endl;
825   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
826   {
827     code << "    fMenuItemDescription" << i << " = (menu.Item(" << i
828          << ") != NULL) ? menu.Item(" << i << ")->Description() : \"\";" << endl;
829   }
830   if (fDebugMode)
831   {
832     code << "    HLTDebug(Form(\"Finished filling description entries from trigger menu.\"));" << endl;
833     code << "    HLTDebug(Form(\"Filling domain entries from trigger menu symbols for global trigger %p.\", this));" << endl;
834   }
835   code << "    for (Int_t i = 0; i < menu.SymbolArray().GetEntriesFast(); i++) {" << endl;
836   // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
837   // Have to use the TClass system for extra protection.
838   code << "      if (menu.SymbolArray().UncheckedAt(i) == NULL) continue;" << endl;
839   code << "      if (menu.SymbolArray().UncheckedAt(i)->IsA() != AliHLTTriggerMenuSymbol::Class()) continue;" << endl;
840   code << "      const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const"
841            " AliHLTTriggerMenuSymbol*>(menu.SymbolArray().UncheckedAt(i));" << endl;
842   code << "      if (symbol == NULL) continue;" << endl;
843   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
844   {
845     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
846     code << "      if (strcmp(symbol->RealName(), \"" << symbol->RealName() << "\") == 0) {" << endl;
847     if (fDebugMode)
848     {
849       code << "        HLTDebug(Form(\"Assinging domain entry value corresponding with symbol '%s' to '%s'.\","
850               " symbol->RealName(), symbol->BlockType().AsString().Data()));" << endl;
851     }
852     code << "        " << symbol->Name() << "DomainEntry = symbol->BlockType();" << endl;
853     code << "        continue;" << endl;
854     code << "      }" << endl;
855   }
856   code << "    }" << endl;
857   if (fDebugMode)
858   {
859     code << "    HLTDebug(Form(\"Finished filling domain entries from trigger menu symbols.\"));" << endl;
860   }
861   code << "  }" << endl;
862   
863   // Generate the NewEvent method.
864   code << "  virtual void NewEvent() {" << endl;
865   if (fDebugMode)
866   {
867     code << "#ifdef __CINT__" << endl;
868     code << "    gFunctionName = \"NewEvent\";" << endl;
869     code << "#endif" << endl;
870     code << "    HLTDebug(Form(\"New event for global trigger object %p, initialising variables to default values.\", this));" << endl;
871   }
872   // Write code to initialise the symbols in the trigger menu to their default values.
873   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
874   {
875     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
876     // CINT has problems with the implicit equals operator for complex types, so if
877     // the type has a equals operater we need to write the operator call explicitly.
878     TClass* clas = TClass::GetClass(symbol->Type());
879     if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
880     {
881       code << "    " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
882     }
883     else
884     {
885       code << "    " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
886     }
887     if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
888     {
889       code << "    " << symbol->Name() << "TriggerDomain.Clear();" << endl;
890     }
891   }
892   if (fDebugMode)
893   {
894     code << "    HLTDebug(Form(\"Finished initialising variables.\"));" << endl;
895   }
896   code << "  }" << endl;
897   
898   // Generate the Add method.
899   bool haveAssignments = false;
900   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
901   {
902     // First check if we have any symbols with assignment expressions.
903     // This is needed to get rid of the on the fly compilation warning about '_object_' not being used.
904     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
905     TString expr = symbol->AssignExpression();
906     if (expr == "") continue; // Skip entries that have no assignment expression.
907     haveAssignments = true;
908     break;
909   }
910   if (haveAssignments or fDebugMode)
911   {
912     code << "  virtual void Add(const TObject* _object_, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
913   }
914   else
915   {
916     code << "  virtual void Add(const TObject* /*_object_*/, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
917   }
918   if (fDebugMode)
919   {
920     code << "#ifdef __CINT__" << endl;
921     code << "    gFunctionName = \"Add\";" << endl;
922     code << "#endif" << endl;
923   }
924   code << "    AliHLTDomainEntry _type_spec_(_type_, _spec_);" << endl;
925   if (fDebugMode)
926   {
927     code << "    HLTDebug(Form(\"Adding TObject %p, with class name '%s' from data block"
928             " '%s', to global trigger object %p\", _object_, _object_->ClassName(),"
929             " _type_spec_.AsString().Data(), this));" << endl;
930     code << "    _object_->Print();" << endl;
931     code << "    bool _object_assigned_ = false;" << endl;
932   }
933   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
934   {
935     // Write code to check if the block type, specification and class name is correct.
936     // Then write code to assign the variable from the input object.
937     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
938     TString expr = symbol->AssignExpression();
939     if (expr == "") continue; // Skip entries that have no assignment expression.
940     bool isTrigDecision = strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0;
941     if (fDebugMode)
942     {
943       if (isTrigDecision)
944       {
945         code << "    HLTDebug(Form(\"Trying to match input object to class '"
946              << symbol->ObjectClass() << "', trigger name '" << symbol->RealName()
947              << "' and block type '%s'\", " << symbol->Name()
948              << "DomainEntry.AsString().Data()));" << endl;
949       }
950       else
951       {
952         code << "    HLTDebug(Form(\"Trying to match input object to class '"
953              << symbol->ObjectClass() << "' and block type '%s'\", "
954              << symbol->Name() << "DomainEntry.AsString().Data()));" << endl;
955       }
956     }
957     // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
958     // Have to use the TClass system for extra protection.
959     code << "    const " << symbol->ObjectClass() << "* " << symbol->Name() << "_object_ = NULL;" << endl;
960     code << "    if (_object_->IsA() == " << symbol->ObjectClass() << "::Class()) " << symbol->Name()
961          << "_object_ = dynamic_cast<const " << symbol->ObjectClass()
962          << "*>(_object_);" << endl;
963     code << "    if (" << symbol->Name() << "_object_ != NULL && ";
964     if (isTrigDecision)
965     {
966       code << "strcmp(" << symbol->Name() << "_object_->Name(), \""
967            << symbol->RealName() << "\") == 0 && ";
968     }
969     code << symbol->Name() << "DomainEntry == _type_spec_) {" << endl;
970     TString fullname = symbol->Name();
971     fullname += "_object_";
972     expr.ReplaceAll("this", fullname);
973     code << "      this->" << symbol->Name() << " = " << expr.Data() << ";" << endl;
974     if (isTrigDecision)
975     {
976       code << "      this->" << symbol->Name() << "TriggerDomain = "
977            << fullname.Data() << "->TriggerDomain();" << endl;
978     }
979     if (fDebugMode)
980     {
981       code << "      HLTDebug(Form(\"Added TObject %p with class name '%s' to variable "
982            << symbol->Name() << "\", _object_, _object_->ClassName()));" << endl;
983       code << "      _object_assigned_ = true;" << endl;
984     }
985     code << "    }" << endl;
986   }
987   if (fDebugMode)
988   {
989     code << "    if (! _object_assigned_) {" << endl;
990     code << "      HLTDebug(Form(\"Did not assign TObject %p"
991             " with class name '%s' to any variable.\", _object_, _object_->ClassName()));"
992          << endl;
993     code << "    }" << endl;
994   }
995   code << "  }" << endl;
996   
997   // Generate the CalculateTriggerDecision method.
998   // This requires code to be generated that checks which items in the trigger menu
999   // have their conditions asserted and then the trigger domain is generated from
1000   // those fired items.
1001   // The processing will start from the highest priority trigger group and stop
1002   // after at least one trigger from the current priority group being processed
1003   // is positive. For each priority group all the trigger menu items are checked.
1004   // Their combined trigger condition expression must be true for the trigger priority
1005   // group to be triggered positive. The full condition expression is formed by
1006   // concatenating the individual condition expressions. If no trailing operators are
1007   // used in the individual expressions then the default condition operator is placed
1008   // between two concatenated condition expressions.
1009   // If a trigger priority group has at least one trigger fired then the trigger domain
1010   // is calculated such that it will give the same result as the concatenated trigger
1011   // domain merging expressions for all the individual trigger menu items with
1012   // positive results. Again, if no trailing operators are used in the individual
1013   // merging expressions then the default domain operator is placed between two
1014   // expression fragments.
1015   code << "  virtual bool CalculateTriggerDecision(AliHLTTriggerDomain& _domain_, TString& _description_) {" << endl;
1016   if (fDebugMode)
1017   {
1018     code << "#ifdef __CINT__" << endl;
1019     code << "    gFunctionName = \"CalculateTriggerDecision\";" << endl;
1020     code << "#endif" << endl;
1021     code << "    HLTDebug(Form(\"Calculating global HLT trigger result with trigger object at %p.\", this));" << endl;
1022   }
1023   
1024   // Build a list of priorities used in the trigger menu.
1025   std::vector<UInt_t> priorities;
1026   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1027   {
1028     const AliHLTTriggerMenuItem* item = menu->Item(i);
1029     bool priorityNotInList = std::find(priorities.begin(), priorities.end(), item->Priority()) == priorities.end();
1030     if (priorityNotInList) priorities.push_back(item->Priority());
1031   }
1032   std::sort(priorities.begin(), priorities.end(), AliHLTDescendingNumbers);
1033   // From the priority list, build the priority groups in the correct order,
1034   // i.e. highest priority first.
1035   // The priority group is a list of vectors of integers. The integers are the
1036   // index numbers into the trigger menu item list for the items which form part
1037   // of the priority group.
1038   std::vector<std::vector<Int_t> > priorityGroup;
1039   priorityGroup.insert(priorityGroup.begin(), priorities.size(), std::vector<Int_t>());
1040   for (size_t n = 0; n < priorities.size(); n++)
1041   {
1042     UInt_t priority = priorities[n];
1043     for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1044     {
1045       const AliHLTTriggerMenuItem* item = menu->Item(i);
1046       if (item->Priority() == priority) priorityGroup[n].push_back(i);
1047     }
1048   }
1049   
1050   for (size_t n = 0; n < priorityGroup.size(); n++)
1051   {
1052     if (fDebugMode)
1053     {
1054       code << "    HLTDebug(Form(\"Processing trigger priority group " << priorities[n] << "\"));" << endl;
1055     }
1056     code << "    ";
1057     if (n == 0) code << "UInt_t ";
1058     code << "_previous_match_ = 0xFFFFFFFF;" << endl;
1059     code << "    ";
1060     if (n == 0) code << "bool ";
1061     code << "_trigger_matched_ = false;" << endl;
1062     code << "    ";
1063     if (n == 0) code << "bool ";
1064     code << "_group_result_ = false;" << endl;
1065     std::vector<TString> conditionOperator;
1066     conditionOperator.insert(conditionOperator.begin(), priorityGroup[n].size(), TString(""));
1067     std::vector<TString> domainOperator;
1068     domainOperator.insert(domainOperator.begin(), priorityGroup[n].size(), TString(""));
1069     for (size_t m = 0; m < priorityGroup[n].size(); m++)
1070     {
1071       UInt_t i = priorityGroup[n][m];
1072       const AliHLTTriggerMenuItem* item = menu->Item(i);
1073       TString triggerCondition = item->TriggerCondition();
1074       TString mergeExpr = item->MergeExpression();
1075       // Replace the symbols found in the trigger condition and merging expressions
1076       // with appropriate compilable versions.
1077       for (Int_t j = 0; j < symbols.GetEntriesFast(); j++)
1078       {
1079         AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(j) );
1080         bool symbolNamesDifferent = strcmp(symbol->RealName(), symbol->Name()) != 0;
1081         if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1082         {
1083           TString newname = symbol->Name();
1084           newname += "TriggerDomain";
1085           mergeExpr.ReplaceAll(symbol->RealName(), newname);
1086         }
1087         else
1088         {
1089           if (symbolNamesDifferent) mergeExpr.ReplaceAll(symbol->RealName(), symbol->Name());
1090         }
1091         if (symbolNamesDifferent) triggerCondition.ReplaceAll(symbol->RealName(), symbol->Name());
1092       }
1093       // We allow the trigger conditions and merging expressions to have trailing operators.
1094       // Thus, we need to extract the operators and cleanup the expressions so that they will
1095       // compile. This means that we silently ignore the trailing operator if not needed.
1096       if (ExtractedOperator(triggerCondition, conditionOperator[m]))
1097       {
1098         // If the trailing operator is the same as the default operator then reset
1099         // the value in the operator list so that the default is used in the generated
1100         // code. This creates more compact code.
1101         if (conditionOperator[m] == menu->DefaultConditionOperator()) conditionOperator[m] = "";
1102       }
1103       if (ExtractedOperator(mergeExpr, domainOperator[m]))
1104       {
1105         if (domainOperator[m] == menu->DefaultDomainOperator()) domainOperator[m] = "";
1106       }
1107       if (fDebugMode)
1108       {
1109         code << "    HLTDebug(Form(\"Trying trigger condition " << i
1110              << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));"
1111              << endl;
1112       }
1113       code << "    ";
1114       if (n == 0 and m == 0) code << "bool ";
1115       code << "_item_result_ = false;" << endl;
1116       code << "    if (" << triggerCondition << ") {" << endl;
1117       code << "      ++fCounter[" << i << "];" << endl;
1118       const char* indentation = "";
1119       if (item->PreScalar() != 0)
1120       {
1121         indentation = "  ";
1122         code << "      if ((fCounter[" << i << "] % " << item->PreScalar() << ") == 1) {" << endl;
1123       }
1124       code << indentation << "      _item_result_ = true;" << endl;
1125       if (fDebugMode)
1126       {
1127         code << indentation << "      HLTDebug(Form(\"Matched trigger condition " << i
1128              << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));" << endl;
1129       }
1130       if (item->PreScalar() != 0)
1131       {
1132         code << "      }" << endl;
1133       }
1134       code << "    }" << endl;
1135       if (m == 0)
1136       {
1137         // Since this is the first item of the trigger group,
1138         // the generated trigger logic can be simplified a little.
1139         code << "    _group_result_ = _item_result_;" << endl;
1140         code << "    if (_item_result_) {" << endl;
1141         code << "      _domain_ = " << mergeExpr.Data() << ";" << endl;
1142         code << "      _description_ = fMenuItemDescription" << i << ";" << endl;
1143         code << "      _previous_match_ = " << i << ";" << endl;
1144         code << "      _trigger_matched_ = true;" << endl;
1145         code << "    }" << endl;
1146       }
1147       else
1148       {
1149         if (conditionOperator[m-1] == "")
1150         {
1151           code << "    _group_result_ = _group_result_ "
1152                << menu->DefaultConditionOperator() << " _item_result_;" << endl;
1153         }
1154         else
1155         {
1156           code << "    _group_result_ = _group_result_ "
1157                << conditionOperator[m-1] << " _item_result_;" << endl;
1158         }
1159         code << "    if (_item_result_) {" << endl;
1160         code << "      if (_trigger_matched_) {" << endl;
1161         bool switchWillBeEmpty = true;
1162         for (size_t k = 0; k < m; k++)
1163         {
1164           if (domainOperator[k] == "") continue;
1165           switchWillBeEmpty = false;
1166         }
1167         if (switchWillBeEmpty)
1168         {
1169           code << "        _domain_ = _domain_ " << menu->DefaultDomainOperator() << " "
1170                << mergeExpr.Data() << ";" << endl;
1171         }
1172         else
1173         {
1174           code << "        switch(_previous_match_) {" << endl;
1175           for (size_t k = 0; k < m; k++)
1176           {
1177             if (domainOperator[k] == "") continue;
1178             code << "        case " << k << ": _domain_ = _domain_ "
1179                  << domainOperator[k] << " " << mergeExpr.Data() << "; break;" << endl;
1180           }
1181           code << "        default: _domain_ = _domain_ "
1182                << menu->DefaultDomainOperator() << " " << mergeExpr.Data() << ";" << endl;
1183           code << "        }" << endl;
1184         }
1185         code << "        _description_ += \",\";" << endl;
1186         code << "        _description_ += fMenuItemDescription" << i << ";" << endl;
1187         code << "      } else {" << endl;
1188         code << "        _domain_ = " << mergeExpr.Data() << ";" << endl;
1189         code << "        _description_ = fMenuItemDescription" << i << ";" << endl;
1190         code << "      }" << endl;
1191         code << "      _previous_match_ = " << i << ";" << endl;
1192         code << "      _trigger_matched_ = true;" << endl;
1193         code << "    }" << endl;
1194       }
1195     }
1196     code << "    if (_group_result_) {" << endl;
1197     if (fDebugMode)
1198     {
1199       if (n < priorities.size() - 1)
1200       {
1201         code << "      HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n]
1202              << ". Stopping processing here because all other trigger groups have lower priority.\"));" << endl;
1203       }
1204       else
1205       {
1206         code << "      HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n] << ".\"));" << endl;
1207       }
1208     }
1209     code << "      return true;" << endl;
1210     code << "    }" << endl;
1211   }
1212   code << "    _domain_.Clear();" << endl;
1213   code << "    _description_ = \"\";" << endl;
1214   code << "    return false;" << endl;
1215   code << "  }" << endl;
1216   
1217   // Generate getter and setter methods for the counters.
1218   code << "  const TArrayL64& GetCounters() const { return fCounter; }" << endl;
1219   code << "  void SetCounters(const TArrayL64& counters) { fCounter = counters; }" << endl;
1220   
1221   code << "private:" << endl;
1222   // Add the symbols in the trigger menu to the list of private variables.
1223   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1224   {
1225     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1226     code << "  " << symbol->Type() << " " << symbol->Name() << ";" << endl;
1227     if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1228     {
1229       code << "  AliHLTTriggerDomain " << symbol->Name() << "TriggerDomain;" << endl;
1230     }
1231     code << "  AliHLTDomainEntry " << symbol->Name() << "DomainEntry;" << endl;
1232   }
1233   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1234   {
1235     code << "  TString fMenuItemDescription" << i << ";" << endl;
1236   }
1237   code << "  TArrayL64 fCounter;" << endl;
1238   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1239   code << "  ClassDef(" << name.Data() << ", 0)" << endl;
1240   code << "#else" << endl;
1241   code << "  virtual const char* Class_Name() const { return \"" << name.Data() << "\"; }" << endl;
1242   code << "#endif" << endl;
1243   code << "};" << endl;
1244   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1245   code << "ClassImp(" << name.Data() << ")" << endl;
1246   code << "#endif" << endl;
1247   
1248   code.close();
1249   
1250   // Now we need to compile and load the new class.
1251   result = LoadTriggerClass(filename, includePaths);
1252   return result;
1253 }
1254
1255
1256 int AliHLTGlobalTriggerComponent::LoadTriggerClass(
1257     const char* filename, const TClonesArray& includePaths
1258   )
1259 {
1260   // Loads the code for a custom global trigger class implementation on the fly.
1261   
1262   HLTDebug("Loading HLT trigger class from file '%s'.", filename);
1263   
1264   TString compiler = gSystem->GetBuildCompilerVersion();
1265   if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1266   {
1267     TString includePath;
1268 #if defined(PKGINCLUDEDIR)
1269     // this is especially for the HLT build system where the package is installed
1270     // in a specific directory including proper treatment of include files
1271     includePath.Form("-I%s", PKGINCLUDEDIR);
1272 #else
1273     // the default AliRoot behavior, all include files can be found in the
1274     // $ALICE_ROOT subfolders
1275     includePath = "-I${ALICE_ROOT}/include -I${ALICE_ROOT}/HLT/BASE -I${ALICE_ROOT}/HLT/trigger";
1276 #endif
1277     // Add any include paths that were specified on the command line.
1278     for (Int_t i = 0; i < includePaths.GetEntriesFast(); i++)
1279     {
1280       TString path = static_cast<TObjString*>(includePaths.UncheckedAt(i))->String();
1281       includePath += " -I";
1282       includePath += path;
1283     }
1284     HLTDebug("using include settings: %s", includePath.Data());
1285     gSystem->SetIncludePath(includePath);
1286     gSystem->SetFlagsOpt("-O3 -DNDEBUG");
1287     gSystem->SetFlagsDebug("-g3 -DDEBUG -D__DEBUG");
1288     
1289     int result = kTRUE;
1290     if (fDebugMode)
1291     {
1292       result = gSystem->CompileMacro(filename, "g");
1293     }
1294     else
1295     {
1296       result = gSystem->CompileMacro(filename, "O");
1297     }
1298     if (result != kTRUE)
1299     {
1300       HLTFatal("Could not compile and load global trigger menu implementation.");
1301       return -ENOENT;
1302     }
1303   }
1304   else
1305   {
1306     // Store the library state to be checked later in UnloadTriggerClass.
1307     fLibStateAtLoad = gSystem->GetLibraries();
1308     
1309     // If we do not support the compiler then try interpret the class instead.
1310     TString cmd = ".L ";
1311     cmd += filename;
1312     Int_t errorcode = TInterpreter::kNoError;
1313     gROOT->ProcessLine(cmd, &errorcode);
1314     if (errorcode != TInterpreter::kNoError)
1315     {
1316       HLTFatal("Could not load interpreted global trigger menu implementation"
1317                " (Interpreter error code = %d).",
1318                errorcode
1319       );
1320       return -ENOENT;
1321     }
1322   }
1323   
1324   return 0;
1325 }
1326
1327
1328 int AliHLTGlobalTriggerComponent::UnloadTriggerClass(const char* filename)
1329 {
1330   // Unloads the code previously loaded by LoadTriggerClass.
1331   
1332   HLTDebug("Unloading HLT trigger class in file '%s'.", filename);
1333   
1334   TString compiler = gSystem->GetBuildCompilerVersion();
1335   if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1336   {
1337     // Generate the library name.
1338     TString libname = filename;
1339     Ssiz_t dotpos = libname.Last('.');
1340     if (0 <= dotpos and dotpos < libname.Length()) libname[dotpos] = '_';
1341     libname += ".";
1342     libname += gSystem->GetSoExt();
1343     
1344     // This is a workaround for a problem with unloading shared libraries in ROOT.
1345     // If the trigger logic library is loaded before the libAliHLTHOMER.so library
1346     // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1347     // call all the subsequent libraries get unloded. This means that any objects created
1348     // from classes implemented in the libAliHLTHOMER.so library will generate segfaults
1349     // since the executable code has been unloaded.
1350     // We need to check if there are any more libraries loaded after the class we
1351     // are unloading and in that case don't unload the class.
1352     TString libstring = gSystem->GetLibraries();
1353     TString token, lastlib;
1354     Ssiz_t from = 0;
1355     Int_t numOfLibs = 0, posOfLib = -1;
1356     while (libstring.Tokenize(token, from, " "))
1357     {
1358       ++numOfLibs;
1359       lastlib = token;
1360       if (token.Contains(libname)) posOfLib = numOfLibs;
1361     }
1362     if (numOfLibs != posOfLib)
1363     {
1364       HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the shared"
1365           " library '%s' since another library '%s' was loaded afterwards. Trying to"
1366           " unload this library will remove the others and lead to serious memory faults.",
1367           libname.Data(), lastlib.Data()
1368       ));
1369       return 0;
1370     }
1371     
1372     char* path = NULL;
1373     int result = 0;
1374     if ((path = gSystem->DynamicPathName(libname)) != NULL)
1375     {
1376       result = gInterpreter->UnloadFile(path);
1377       delete [] path;
1378     }
1379     if (result != TInterpreter::kNoError) return -ENOENT;
1380   }
1381   else
1382   {
1383     // This is again a workaround for the problem with unloading files in ROOT.
1384     // If the trigger logic class is loaded before the libAliHLTHOMER.so library
1385     // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1386     // call all the subsequent libraries get unloded.
1387     // We need to check if the list of loaded libraries has changed since the last
1388     // call to LoadTriggerClass. If it has then don't unload the class.
1389     if (fLibStateAtLoad != gSystem->GetLibraries())
1390     {
1391       TString libstring = gSystem->GetLibraries();
1392       TString token;
1393       Ssiz_t from = 0;
1394       while (libstring.Tokenize(token, from, " "))
1395       {
1396         if (not fLibStateAtLoad.Contains(token)) break;
1397       }
1398       HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the file"
1399           " '%s' since another library '%s' was loaded afterwards. Trying to unload"
1400           " this file will remove the other library and lead to serious memory faults.",
1401           filename, token.Data()
1402       ));
1403       return 0;
1404     }
1405   
1406     // If we did not compile the trigger logic then remove the interpreted class.
1407     TString cmd = ".U ";
1408     cmd += filename;
1409     Int_t errorcode = TInterpreter::kNoError;
1410     gROOT->ProcessLine(cmd, &errorcode);
1411     if (errorcode != TInterpreter::kNoError)
1412     {
1413       HLTFatal("Could not unload interpreted global trigger menu implementation"
1414                " (Interpreter error code = %d).",
1415                errorcode
1416       );
1417       return -ENOENT;
1418     }
1419   }
1420   
1421   return 0;
1422 }
1423
1424
1425 int AliHLTGlobalTriggerComponent::FindSymbol(const char* name, const TClonesArray& list)
1426 {
1427   // Searches for the named symbol in the given list.
1428   // See header for more details.
1429   
1430   for (int i = 0; i < list.GetEntriesFast(); i++)
1431   {
1432     const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(i) );
1433     if (symbol == NULL) continue;
1434     if (strcmp(symbol->Name(), name) == 0) return i;
1435   }
1436   return -1;
1437 }
1438
1439
1440 int AliHLTGlobalTriggerComponent::BuildSymbolList(const AliHLTTriggerMenu* menu, TClonesArray& list)
1441 {
1442   // Builds the list of symbols to use in the custom global trigger menu
1443   // implementation class.
1444   // See header for more details.
1445   
1446   // Note: when we build the symbol list we must use the symbol name as returned
1447   // by the Name() method and not the RealName() method when using FindSymbol.
1448   // This is so that we avoid problems with the generated code not compiling
1449   // because names like "abc-xyz" and "abc_xyz" are synonymous.
1450   // Name() returns the converted C++ symbol name as used in the generated code.
1451   
1452   for (UInt_t i = 0; i < menu->NumberOfSymbols(); i++)
1453   {
1454     const AliHLTTriggerMenuSymbol* symbol = menu->Symbol(i);
1455     if (FindSymbol(symbol->Name(), list) != -1)
1456     {
1457       HLTError("Multiple symbols with the name '%s' defined in the trigger menu.", symbol->Name());
1458       return -EIO;
1459     }
1460     try
1461     {
1462       new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(*symbol);
1463     }
1464     catch (const std::bad_alloc&)
1465     {
1466       HLTError("Could not allocate more memory for the symbols list when adding a trigger menu symbol.");
1467       return -ENOMEM;
1468     }
1469   }
1470   
1471   TRegexp exp("[_a-zA-Z][-_a-zA-Z0-9]*");
1472   TRegexp hexexp("x[a-fA-F0-9]+");
1473   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1474   {
1475     const AliHLTTriggerMenuItem* item = menu->Item(i);
1476     TString str = item->TriggerCondition();
1477     Ssiz_t start = 0;
1478     do
1479     {
1480       Ssiz_t length = 0;
1481       Ssiz_t pos = exp.Index(str, &length, start);
1482       if (pos == kNPOS) break;
1483       start = pos+length;
1484       
1485       // Check if there is a numerical character before the found
1486       // regular expression. If so, then the symbol is not a valid one
1487       // and should be skipped.
1488       if (pos > 0)
1489       {
1490         bool notValid = false;
1491         switch (str[pos-1])
1492         {
1493         case '0': case '1': case '2': case '3': case '4':
1494         case '5': case '6': case '7': case '8': case '9':
1495           notValid = true;
1496           break;
1497         default:
1498           notValid = false;
1499           break;
1500         }
1501         if (notValid) continue;
1502       }
1503       TString s = str(pos, length);
1504       
1505       if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1506           s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1507           s == "or_eq" or s == "xor" or s == "xor_eq" or s == "true" or
1508           s == "false"
1509          )
1510       {
1511         // Ignore iso646.h and other keywords.
1512         continue;
1513       }
1514
1515       // Need to create the symbols first and check if its name is in the list
1516       // before actually adding it to the symbols list.
1517       AliHLTTriggerMenuSymbol newSymbol;
1518       newSymbol.Name(s.Data());
1519       newSymbol.Type("bool");
1520       newSymbol.ObjectClass("AliHLTTriggerDecision");
1521       newSymbol.AssignExpression("this->Result()");
1522       newSymbol.DefaultValue("false");
1523       if (FindSymbol(newSymbol.Name(), list) == -1)
1524       {
1525         try
1526         {
1527           new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(newSymbol);
1528         }
1529         catch (const std::bad_alloc&)
1530         {
1531           HLTError("Could not allocate more memory for the symbols list when adding a trigger name symbol.");
1532           return -ENOMEM;
1533         }
1534       }
1535     }
1536     while (start < str.Length());
1537   }
1538   
1539   return 0;
1540 }
1541
1542
1543 bool AliHLTGlobalTriggerComponent::ExtractedOperator(TString& expr, TString& op)
1544 {
1545   // Extracts the trailing operator from the expression.
1546   
1547   Ssiz_t i = 0;
1548   // First skip the trailing whitespace.
1549   bool whitespace = true;
1550   for (i = expr.Length()-1; i >= 0 and whitespace; i--)
1551   {
1552     switch (expr[i])
1553     {
1554     case ' ': case '\t': case '\r': case '\n':
1555       whitespace = true;
1556       break;
1557     default:
1558       whitespace = false;
1559     }
1560   }
1561   if (i < 0 or whitespace) return false;
1562   
1563   // Now find the first whitespace character before the trailing symbol.
1564   bool nonwhitespace = true;
1565   for (; i >= 0 and nonwhitespace; i--)
1566   {
1567     switch (expr[i])
1568     {
1569     case ' ': case '\t': case '\r': case '\n':
1570       nonwhitespace = false;
1571       break;
1572     default:
1573       nonwhitespace = true;
1574     }
1575   }
1576   if (i < 0 or nonwhitespace) return false;
1577   
1578   // Extract the last symbols and check if it is a valid operator.
1579   TString s = expr;
1580   s.Remove(0, i+2);
1581   if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1582       s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1583       s == "or_eq" or s == "xor" or s == "xor_eq" or s == "&&" or
1584       s == "&=" or s == "&" or s == "|" or s == "~" or s == "!" or
1585       s == "!=" or s == "||" or s == "|=" or s == "^" or s == "^=" or
1586       s == "==" or s == "+" or s == "-" or s == "*" or s == "/" or
1587       s == "%" or s == ">" or s == "<" or s == ">=" or s == "<="
1588      )
1589   {
1590     expr.Remove(i+1);
1591     op = s;
1592     return true;
1593   }
1594   
1595   return false;
1596 }
1597
1598
1599 int AliHLTGlobalTriggerComponent::PrintStatistics(const AliHLTGlobalTrigger* pTrigger, AliHLTComponentLogSeverity level, int offset) const
1600 {
1601   // print some statistics
1602   int totalEvents=GetEventCount()+offset;
1603   const TArrayL64& counters = pTrigger->GetCounters();
1604   if (pTrigger->CallFailed()) return -EPROTO;
1605   for (int i = 0; i < counters.GetSize(); i++) {
1606     ULong64_t count = counters[i];
1607     float ratio=0;
1608     if (totalEvents>0) ratio=100*(float)count/totalEvents;
1609     HLTLog(level, "Item %d: total events: %d - counted events: %llu (%.1f%%)", i, totalEvents, count, ratio);
1610   }
1611   return 0;
1612 }
1613
1614 int AliHLTGlobalTriggerComponent::AddCTPDecisions(AliHLTGlobalTrigger* pTrigger, const AliHLTCTPData* pCTPData, const AliHLTComponentTriggerData* trigData)
1615 {
1616   // add trigger decisions for the valid CTP classes
1617   if (!pCTPData || !pTrigger) return 0;
1618
1619   AliHLTUInt64_t triggerMask=pCTPData->Mask();
1620   AliHLTUInt64_t bit0=0x1;
1621   if (!fCTPDecisions) {
1622     try
1623     {
1624       fCTPDecisions=new TClonesArray(AliHLTTriggerDecision::Class(), gkNCTPTriggerClasses);
1625     }
1626     catch (const std::bad_alloc&)
1627     {
1628       HLTError("Could not allocate memory for the CTP decisions array.");
1629       return -ENOMEM;
1630     }
1631     if (!fCTPDecisions) return -ENOMEM;
1632
1633     try
1634     {
1635       fCTPDecisions->ExpandCreate(gkNCTPTriggerClasses);
1636     }
1637     catch (const std::bad_alloc&)
1638     {
1639       HLTError("Could not allocate more memory for the CTP decisions array.");
1640       return -ENOMEM;
1641     }
1642     for (int i=0; i<gkNCTPTriggerClasses; i++) {
1643       const char* name=pCTPData->Name(i);
1644       if (triggerMask&(bit0<<i) && name) {
1645         AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1646         assert(pDecision);
1647         if (!pDecision) {
1648           delete fCTPDecisions;
1649           fCTPDecisions=NULL;
1650           return -ENOENT;
1651         }
1652         pDecision->Name(name);
1653       }
1654     }
1655   }
1656
1657   for (int i=0; i<gkNCTPTriggerClasses; i++) {
1658     const char* name=pCTPData->Name(i);
1659     if ((triggerMask&(bit0<<i))==0 || name==NULL) continue;
1660     AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1661     HLTDebug("updating CTP trigger decision %d %s (%p casted %p)", i, name, fCTPDecisions->At(i), pDecision);
1662     if (!pDecision) return -ENOENT;
1663
1664     bool result=false;
1665     if (trigData) result=pCTPData->EvaluateCTPTriggerClass(name, *trigData);
1666     else result=pCTPData->EvaluateCTPTriggerClass(name);
1667     pDecision->Result(result);
1668     pDecision->TriggerDomain().Clear();
1669     if (trigData) pDecision->TriggerDomain().Add(pCTPData->ReadoutList(*trigData));
1670     else pDecision->TriggerDomain().Add(pCTPData->ReadoutList());
1671
1672     pTrigger->Add(fCTPDecisions->At(i), kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
1673     if (pTrigger->CallFailed()) return -EPROTO;
1674   }
1675
1676   return 0;
1677 }