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