From 4c7d93590851955d87377e7dd14d717af7a72b23 Mon Sep 17 00:00:00 2001
From: Markus Frank <Markus.Frank@cern.ch>
Date: Fri, 10 Mar 2017 12:05:50 +0100
Subject: [PATCH] New round to kill coverity deficiencies.

---
 DDCond/src/ConditionsTextRepository.cpp       | 14 ++++++---
 DDCond/src/plugins/ConditionsParser.cpp       | 10 +++++--
 .../plugins/ConditionsRepositoryParser.cpp    |  6 ++--
 DDCore/src/plugins/StandardPlugins.cpp        |  2 +-
 DDDB/src/DDDBFileReader.cpp                   |  4 +--
 DDEve/src/DisplayConfigurationParser.cpp      |  8 +++--
 UtilityApps/src/graphicalMaterialScan.cpp     |  6 +++-
 UtilityApps/src/main.h                        | 30 +++++++++++++++++++
 UtilityApps/src/materialScan.cpp              |  3 +-
 UtilityApps/src/print_materials.cpp           |  3 +-
 UtilityApps/src/test_surfaces.cpp             |  3 +-
 doc/release.notes                             |  6 ++++
 12 files changed, 75 insertions(+), 20 deletions(-)
 create mode 100644 UtilityApps/src/main.h

diff --git a/DDCond/src/ConditionsTextRepository.cpp b/DDCond/src/ConditionsTextRepository.cpp
index 6ce24540c..1889c8c97 100644
--- a/DDCond/src/ConditionsTextRepository.cpp
+++ b/DDCond/src/ConditionsTextRepository.cpp
@@ -154,10 +154,16 @@ namespace {
       text[0] = 0;
       in.getline(text,sizeof(text),'\n');
       if ( in.good() )  {
-        if ( siz_tot )  {
+        if ( 9+siz_nam >= sizeof(text) )
+          except("ConditionsTextRepository","Inconsistent input data in %s: %s -> (%lld,%lld,%lld)",
+                 __FILE__, input.c_str(), siz_nam, siz_add, siz_tot);
+        else if ( 10+siz_nam+siz_add >= sizeof(text) )
+          except("ConditionsTextRepository","Inconsistent input data in %s: %s -> (%lld,%lld,%lld)",
+                 __FILE__, input.c_str(), siz_nam, siz_add, siz_tot);
+        else if ( siz_tot )  {
           // Direct access mode with fixed record size
-          text[8] = text[9+siz_nam] = text[10+siz_nam+siz_add] = 0;
-          e.name = text+9;
+          text[8]   = text[9+siz_nam] = text[10+siz_nam+siz_add] = 0;
+          e.name    = text+9;
           e.address = text+10+siz_nam;  
           if ( (idx=e.name.find(' ')) != string::npos )
             e.name[idx]=0;
@@ -167,7 +173,7 @@ namespace {
         else  {
           // Variable record size
           e.name=text+9;
-          if ( (idx=e.name.find(sep)) != string::npos )
+          if ( (idx=e.name.find(sep)) != string::npos && idx+10 < sizeof(text) )
             text[9+idx]=0, e.address=text+idx+10, e.name=text+9;
           if ( (idx=e.address.find(sep)) != string::npos )
             e.address[idx]=0;
diff --git a/DDCond/src/plugins/ConditionsParser.cpp b/DDCond/src/plugins/ConditionsParser.cpp
index d58534810..8f1bb82dd 100644
--- a/DDCond/src/plugins/ConditionsParser.cpp
+++ b/DDCond/src/plugins/ConditionsParser.cpp
@@ -154,12 +154,18 @@ namespace DD4hep {
     else if ( tag == "alignment" )   {
       dd4hep_ptr<Entry> val(_createStackEntry(param,e));
       val->value = elt.attr<string>(_U(ref));
-      arg->stack->push_back(val.release());
+      if ( !arg->stack )
+        except("ConditionsParser","Non-existing Conditions stack:%s %d",__FILE__, __LINE__);
+      else
+        arg->stack->push_back(val.release());
     }
     else  {
       dd4hep_ptr<Entry> val(_createStackEntry(param,e));
       val->value = elt.hasAttr(_U(value)) ? elt.valueStr() : e.text();
-      arg->stack->push_back(val.release());
+      if ( !arg->stack )
+        except("ConditionsParser","Non-existing Conditions stack:%s %d",__FILE__, __LINE__);
+      else
+        arg->stack->push_back(val.release());
     }
   }
 
diff --git a/DDCond/src/plugins/ConditionsRepositoryParser.cpp b/DDCond/src/plugins/ConditionsRepositoryParser.cpp
index 6b85a6018..fee0e8ca8 100644
--- a/DDCond/src/plugins/ConditionsRepositoryParser.cpp
+++ b/DDCond/src/plugins/ConditionsRepositoryParser.cpp
@@ -209,12 +209,12 @@ namespace DD4hep {
   template <> void Converter<iov_type>::operator()(xml_h element) const {
     xml_dim_t e   = element;
     string    nam = e.nameStr();
-    int       id  = e.id();
+    size_t    id  = e.id();
     ConversionArg* arg  = _param<ConversionArg>();
-    printout(s_parseLevel,"XMLConditions","++ Registering IOV type: [%d]: %s",id,nam.c_str());
+    printout(s_parseLevel,"XMLConditions","++ Registering IOV type: [%d]: %s",int(id),nam.c_str());
     const IOVType* iov_type = arg->manager.registerIOVType(id,nam).second;
     if ( !iov_type )   {
-      except("XMLConditions","Failed to register iov type: [%d]: %s",id,nam.c_str());
+      except("XMLConditions","Failed to register iov type: [%d]: %s",int(id),nam.c_str());
     }
   }
 
diff --git a/DDCore/src/plugins/StandardPlugins.cpp b/DDCore/src/plugins/StandardPlugins.cpp
index e1645647b..55dd26b78 100644
--- a/DDCore/src/plugins/StandardPlugins.cpp
+++ b/DDCore/src/plugins/StandardPlugins.cpp
@@ -624,7 +624,7 @@ static long dump_volume_tree(LCDD& lcdd, int argc, char** argv) {
         }
         printout(INFO,"VolumeDump",fmt,"",
                  aligned->GetName(),
-                 volume->GetShape()->IsA()->GetName(),
+                 volume ? volume->GetShape()->IsA()->GetName() : "[Invalid Volume]",
                  opt_info.c_str());
       }
       for (Int_t idau = 0, ndau = aligned->GetNdaughters(); idau < ndau; ++idau)  {
diff --git a/DDDB/src/DDDBFileReader.cpp b/DDDB/src/DDDBFileReader.cpp
index 74c46b286..c8bef7ae4 100644
--- a/DDDB/src/DDDBFileReader.cpp
+++ b/DDDB/src/DDDBFileReader.cpp
@@ -71,7 +71,7 @@ int DD4hep::DDDB::DDDBFileReader::getObject(const std::string& system_id,
   struct stat buff;
   if ( 0 == ::stat(path.c_str(), &buff) )  {
     int fid  = ::open(path.c_str(), O_RDONLY);
-    if ( fid != 0 )   {
+    if ( fid > 0 )   {
       int done = 0, len = buff.st_size;
       char* b  = new char[len+1];
       b[0] = 0;
@@ -85,10 +85,8 @@ int DD4hep::DDDB::DDDBFileReader::getObject(const std::string& system_id,
       buffer = b;
       delete [] b;
       if ( done>=len ) {
-        ::close(fid);
         return 1;
       }
-      ::close(fid);
     }
   }
   return 0;
diff --git a/DDEve/src/DisplayConfigurationParser.cpp b/DDEve/src/DisplayConfigurationParser.cpp
index d8451d14c..4b853e615 100644
--- a/DDEve/src/DisplayConfigurationParser.cpp
+++ b/DDEve/src/DisplayConfigurationParser.cpp
@@ -1,4 +1,3 @@
-// $Id: $
 //==========================================================================
 //  AIDA Detector description implementation for LCD
 //--------------------------------------------------------------------------
@@ -248,8 +247,11 @@ template <> void Converter<collection>::operator()(xml_h e)  const  {
 template <> void Converter<include>::operator()(xml_h e)  const  {
   if ( e )  {
     LCDDLoad* load = dynamic_cast<LCDDLoad*>(&this->lcdd);
-    load->processXML(e,e.attr<string>(_U(ref)));
-    return;
+    if ( load )   {
+      load->processXML(e,e.attr<string>(_U(ref)));
+      return;
+    }
+    except("DisplayConfiguration","++ Invalid LCDDLoad instance in XML converter <include>");
   }
   except("DisplayConfiguration","++ Attempt to parse invalid include statement [Invalid XML element]");
 }
diff --git a/UtilityApps/src/graphicalMaterialScan.cpp b/UtilityApps/src/graphicalMaterialScan.cpp
index ab3fb19ac..772b88730 100644
--- a/UtilityApps/src/graphicalMaterialScan.cpp
+++ b/UtilityApps/src/graphicalMaterialScan.cpp
@@ -33,6 +33,7 @@
 #include "DDRec/MaterialManager.h"
 
 #include <iostream>
+#include <cerrno>
 #include <string>
 #include <map>
 
@@ -108,7 +109,10 @@ int main_wrapper(int argc, char** argv)   {
     argv[6] << " " << argv[7] << " " << argv[8] << " " << 
     argv[9] << " " << argv[10] << " " << argv[11] << " " << "NONE";
   sstr >> x0 >> y0 >> z0 >> x1 >> y1 >> z1 >> nslice >> nbins >> mm;
-  if ( !sstr.good() ) Handler::usage();
+  if ( !sstr.good() )   {
+    Handler::usage();
+    ::exit(EINVAL);
+  }
 
   if ( x0>x1 ) { double temp=x0; x0=x1; x1=temp; }
   if ( y0>y1 ) { double temp=y0; y0=y1; y1=temp; }
diff --git a/UtilityApps/src/main.h b/UtilityApps/src/main.h
new file mode 100644
index 000000000..319fac963
--- /dev/null
+++ b/UtilityApps/src/main.h
@@ -0,0 +1,30 @@
+//==========================================================================
+//  AIDA Detector description implementation for LCD
+//--------------------------------------------------------------------------
+// Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
+// All rights reserved.
+//
+// For the licensing terms see $DD4hepINSTALL/LICENSE.
+// For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
+//
+// Author     : M.Frank
+//
+//==========================================================================
+#include <stdexcept>
+#include <iostream>
+
+int main_wrapper(int argc, char** argv );
+
+///  Mini wrapper to call main exception safe ....
+int main(int argc, char** argv)  {
+  try {
+    return main_wrapper(argc,argv);
+  }
+  catch(const std::exception& e)  {
+    std::cout << "Got uncaught exception: " << e.what() << std::endl;
+  }
+  catch (...)  {
+    std::cout << "Got UNKNOWN uncaught exception." << std::endl;
+  }
+  return EINVAL;    
+}
diff --git a/UtilityApps/src/materialScan.cpp b/UtilityApps/src/materialScan.cpp
index 9a33bbd3a..515aba1e9 100644
--- a/UtilityApps/src/materialScan.cpp
+++ b/UtilityApps/src/materialScan.cpp
@@ -23,12 +23,13 @@
 #include "DD4hep/LCDD.h"
 #include "DD4hep/Printout.h"
 #include "DDRec/MaterialManager.h"
+#include "main.h"
 
 using namespace DD4hep;
 using namespace DDRec;
 using DDSurfaces::Vector3D;
 
-int main(int argc, char** argv)   {
+int main_wrapper(int argc, char** argv)   {
   struct Handler  {
     Handler() { SetErrorHandler(Handler::print); }
     static void print(int level, Bool_t abort, const char *location, const char *msg)  {
diff --git a/UtilityApps/src/print_materials.cpp b/UtilityApps/src/print_materials.cpp
index f60764a92..889a3dfde 100644
--- a/UtilityApps/src/print_materials.cpp
+++ b/UtilityApps/src/print_materials.cpp
@@ -28,8 +28,9 @@ using namespace DDSurfaces ;
 using namespace dd4hep ;
 
 //=============================================================================
+#include "main.h"
 
-int main(int argc, char** argv ){
+int main_wrapper(int argc, char** argv ){
     
   if( argc != 8 ) {
     std::cout << " usage: print_materials compact.xml x0 y0 z0 x1 y1 z1 " << std::endl 
diff --git a/UtilityApps/src/test_surfaces.cpp b/UtilityApps/src/test_surfaces.cpp
index 13d9e84b0..a7c177ddf 100644
--- a/UtilityApps/src/test_surfaces.cpp
+++ b/UtilityApps/src/test_surfaces.cpp
@@ -43,7 +43,7 @@ static DDTest test( "surfaces" ) ;
 
 //=============================================================================
 
-int main(int argc, char** argv ){
+int main_wrapper(int argc, char** argv ){
 
   if( argc < 3 ) {
     std::cout << " usage: test_surfaces compact.xml lcio_file.slcio" << std::endl ;
@@ -219,3 +219,4 @@ int main(int argc, char** argv ){
 }
 
 //=============================================================================
+#include "main.h"
diff --git a/doc/release.notes b/doc/release.notes
index 97c8c7d2e..106b80a0b 100644
--- a/doc/release.notes
+++ b/doc/release.notes
@@ -4,6 +4,12 @@ DD4hep  ----  Release Notes
 =================================
 
 
+
+ Markus Frank 2017-03-10
+ -- New round to kill coverity deficiencies.
+ -- Add exception try-catch clauses around various main programs in UtilityApps
+    See UtilityApps/src/main.h for details.
+
  Markus Frank 2017-03-09
  -- Fix issue with long volume ids exceeding 32 bits.
     Test added in examples/ClientTests
-- 
GitLab