From b28fdf12e316ce5cecccb32d44c9f68ec86e92aa Mon Sep 17 00:00:00 2001
From: Dan Guest <dguest@cern.ch>
Date: Mon, 3 Sep 2018 21:42:59 +0200
Subject: [PATCH] Fix segfault when ttree2hdf5 runs on empty files

When ttree2hdf5 was passed and empty file would segfault. This commit
adds some protection against that situation. I also added a thin
wrapper on the `main(...)` function to catch logic errors and make the
error handling slightly cleaner.


Former-commit-id: 7bff2a1bb32a01992738e5d709136c21c9989535
---
 .../AnalysisCommon/HDF5Utils/util/getTree.cxx         |  3 +++
 .../AnalysisCommon/HDF5Utils/util/ttree2hdf5.cxx      | 11 +++++++++++
 2 files changed, 14 insertions(+)

diff --git a/PhysicsAnalysis/AnalysisCommon/HDF5Utils/util/getTree.cxx b/PhysicsAnalysis/AnalysisCommon/HDF5Utils/util/getTree.cxx
index 34dc02661a9..1b8a468a5a5 100644
--- a/PhysicsAnalysis/AnalysisCommon/HDF5Utils/util/getTree.cxx
+++ b/PhysicsAnalysis/AnalysisCommon/HDF5Utils/util/getTree.cxx
@@ -43,6 +43,9 @@ namespace H5Utils {
     }
     std::set<std::string> keys;
     int n_keys = file->GetListOfKeys()->GetSize();
+    if (n_keys == 0) {
+      throw std::logic_error("no keys found in file");
+    }
     for (int keyn = 0; keyn < n_keys; keyn++) {
       keys.insert(file->GetListOfKeys()->At(keyn)->GetName());
     }
diff --git a/PhysicsAnalysis/AnalysisCommon/HDF5Utils/util/ttree2hdf5.cxx b/PhysicsAnalysis/AnalysisCommon/HDF5Utils/util/ttree2hdf5.cxx
index 3f7929f5f94..0b67ad68836 100644
--- a/PhysicsAnalysis/AnalysisCommon/HDF5Utils/util/ttree2hdf5.cxx
+++ b/PhysicsAnalysis/AnalysisCommon/HDF5Utils/util/ttree2hdf5.cxx
@@ -14,7 +14,18 @@ Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
 #include <iostream>
 #include <memory>
 
+int run(int argc, char* argv[]);
+
 int main(int argc, char* argv[]) {
+  try {
+    return run(argc, argv);
+  } catch (std::logic_error& e) {
+    std::cerr << "ERROR: " << e.what() << ", quitting." << std::endl;
+    return 1;
+  }
+}
+
+int run(int argc, char* argv[]) {
   using namespace H5Utils;
   AppOpts opts = getTreeCopyOpts(argc, argv);
 
-- 
GitLab