From e40351a2d670c4358359860916db5d3ca3176bab Mon Sep 17 00:00:00 2001
From: Shaun Roe <shaun.roe@cern.ch>
Date: Fri, 1 Nov 2024 17:55:36 +0100
Subject: [PATCH] sanitise input

---
 Control/AthenaMonitoring/src/AthMonBench.cxx | 37 ++++++++++++--------
 Control/AthenaMonitoring/src/AthMonBench.h   | 15 ++++----
 2 files changed, 28 insertions(+), 24 deletions(-)

diff --git a/Control/AthenaMonitoring/src/AthMonBench.cxx b/Control/AthenaMonitoring/src/AthMonBench.cxx
index 30e5fb55e4fa..c338867923f5 100644
--- a/Control/AthenaMonitoring/src/AthMonBench.cxx
+++ b/Control/AthenaMonitoring/src/AthMonBench.cxx
@@ -3,25 +3,32 @@
 */
 
 #include "AthMonBench.h"
-#include <cstring>
-#include <stdio.h>
+#include <iostream>
+#include <limits>
+#include <fstream>
 
-AthMonBench::TMem AthMonBench::currentVMem()
-{
+namespace{
+  template <long f>
+  long
+  multiply(long result){
+    static constexpr long maxval = std::numeric_limits<long>::max()/f;
+    if ((result>maxval) or (result<0)) return -1;
+    return result * f;
+  }
+}
+
+AthMonBench::TMem 
+AthMonBench::currentVMem(){
   long result = -1;
-  FILE* file = fopen("/proc/self/status", "r");
-  if (!file)
-    return result;
-  char line[128];
-  while (fgets(line, 128, file) != NULL){
-    if (strncmp(line, "VmSize:", 7) == 0) {
-      std::stringstream s(&(line[7]));
-      s >> result;
-      result *= 1024;//NB: ~1K uncertainty
-      break;
+  std::ifstream file("/proc/self/status");
+  const std::string search{"VmSize:"};
+  std::string line;
+  while(getline(file, line)) { 
+    if (line.starts_with(search)) {
+      result = std::stol(line.substr(search.size()));
+      result = multiply<1024L>(result);
     }
   }
-  fclose(file);
   return result;
 }
 
diff --git a/Control/AthenaMonitoring/src/AthMonBench.h b/Control/AthenaMonitoring/src/AthMonBench.h
index c461486d1dff..20f6c6714cd6 100644
--- a/Control/AthenaMonitoring/src/AthMonBench.h
+++ b/Control/AthenaMonitoring/src/AthMonBench.h
@@ -19,8 +19,7 @@
 #define ATHMONBENCH_H
 
 #include <ctime>
-#include <sstream>
-#include <ostream>
+#include <iosfwd>
 #include "GaudiKernel/IMessageSvc.h"
 
 class AthMonBench {
@@ -28,7 +27,7 @@ public:
 
   static const MSG::Level s_resourceMonThreshold = MSG::DEBUG;
 
-  AthMonBench();
+  AthMonBench() = default;
   ~AthMonBench() = default;
 
   //Modify:
@@ -51,9 +50,9 @@ public:
 
 private:
   typedef long long TMem;//bytes
-  TMem m_deltaMem;
-  clock_t m_deltaCPU;
-  int m_count;
+  TMem m_deltaMem{};
+  clock_t m_deltaCPU{};
+  int m_count{};
   static TMem currentVMem();
 };
 
@@ -62,10 +61,8 @@ std::ostream& operator << ( std::ostream& os, const AthMonBench& br);
 /////////////
 // Inlines //
 /////////////
-inline AthMonBench::AthMonBench() { reset(); }
 
-inline void AthMonBench::reset()
-{
+inline void AthMonBench::reset(){
   m_deltaMem = 0;
   m_deltaCPU = 0;
   m_count = 0;
-- 
GitLab