c884a03
diff --git a/src/actions.cpp b/src/actions.cpp
c884a03
index 35c7965..cb905f6 100644
c884a03
--- a/src/actions.cpp
c884a03
+++ b/src/actions.cpp
c884a03
@@ -59,6 +59,7 @@ EXIV2_RCSID("@(#) $Id: actions.cpp 4719 2017-03-08 20:42:28Z robinwmills $")
c884a03
 #include <ctime>
c884a03
 #include <cmath>
c884a03
 #include <cassert>
c884a03
+#include <stdexcept>
c884a03
 #include <sys/types.h>                  // for stat()
c884a03
 #include <sys/stat.h>                   // for stat()
c884a03
 #ifdef EXV_HAVE_UNISTD_H
c884a03
@@ -236,33 +237,43 @@ namespace Action {
c884a03
     }
c884a03
c884a03
     int Print::run(const std::string& path)
c884a03
-    try {
c884a03
-        path_ = path;
c884a03
-        int rc = 0;
c884a03
-        Exiv2::PrintStructureOption option = Exiv2::kpsNone ;
c884a03
-        switch (Params::instance().printMode_) {
c884a03
-            case Params::pmSummary:   rc = printSummary();     break;
c884a03
-            case Params::pmList:      rc = printList();        break;
c884a03
-            case Params::pmComment:   rc = printComment();     break;
c884a03
-            case Params::pmPreview:   rc = printPreviewList(); break;
c884a03
-            case Params::pmStructure: rc = printStructure(std::cout,Exiv2::kpsBasic)     ; break;
c884a03
-            case Params::pmRecursive: rc = printStructure(std::cout,Exiv2::kpsRecursive) ; break;
c884a03
-
c884a03
-            case Params::pmXMP:
c884a03
-                 option = option == Exiv2::kpsNone ? Exiv2::kpsXMP        : option;  // drop
c884a03
-            case Params::pmIccProfile:{
c884a03
-                 option = option == Exiv2::kpsNone ? Exiv2::kpsIccProfile : option;
c884a03
-                 _setmode(_fileno(stdout),O_BINARY);
c884a03
-                 rc = printStructure(std::cout,option);
c884a03
-            } break;
c884a03
+    {
c884a03
+        try {
c884a03
+            path_ = path;
c884a03
+            int rc = 0;
c884a03
+            Exiv2::PrintStructureOption option = Exiv2::kpsNone ;
c884a03
+            switch (Params::instance().printMode_) {
c884a03
+                case Params::pmSummary:   rc = printSummary();     break;
c884a03
+                case Params::pmList:      rc = printList();        break;
c884a03
+                case Params::pmComment:   rc = printComment();     break;
c884a03
+                case Params::pmPreview:   rc = printPreviewList(); break;
c884a03
+                case Params::pmStructure: rc = printStructure(std::cout,Exiv2::kpsBasic)     ; break;
c884a03
+                case Params::pmRecursive: rc = printStructure(std::cout,Exiv2::kpsRecursive) ; break;
c884a03
+
c884a03
+                case Params::pmXMP:
c884a03
+                    if (option == Exiv2::kpsNone)
c884a03
+                        option = Exiv2::kpsXMP;
c884a03
+                    // drop
c884a03
+                case Params::pmIccProfile:
c884a03
+                    if (option == Exiv2::kpsNone)
c884a03
+                        option = Exiv2::kpsIccProfile;
c884a03
+                    _setmode(_fileno(stdout),O_BINARY);
c884a03
+                    rc = printStructure(std::cout,option);
c884a03
+                    break;
c884a03
+            }
c884a03
+            return rc;
c884a03
+        }
c884a03
+        catch(const Exiv2::AnyError& e) {
c884a03
+            std::cerr << "Exiv2 exception in print action for file "
c884a03
+                      << path << ":\n" << e << "\n";
c884a03
+            return 1;
c884a03
+        }
c884a03
+        catch(const std::overflow_error& e) {
c884a03
+            std::cerr << "std::overflow_error exception in print action for file "
c884a03
+                      << path << ":\n" << e.what() << "\n";
c884a03
+            return 1;
c884a03
         }
c884a03
-        return rc;
c884a03
     }
c884a03
-    catch(const Exiv2::AnyError& e) {
c884a03
-        std::cerr << "Exiv2 exception in print action for file "
c884a03
-                  << path << ":\n" << e << "\n";
c884a03
-        return 1;
c884a03
-    } // Print::run
c884a03
c884a03
     int Print::printStructure(std::ostream& out, Exiv2::PrintStructureOption option)
c884a03
     {
c884a03
diff --git a/src/jp2image.cpp b/src/jp2image.cpp
c884a03
index ac31257..4c072d7 100644
c884a03
--- a/src/jp2image.cpp
c884a03
+++ b/src/jp2image.cpp
c884a03
@@ -41,6 +41,7 @@ EXIV2_RCSID("@(#) $Id: jp2image.cpp 4759 2017-04-23 10:58:54Z robinwmills $")
c884a03
 #include "error.hpp"
c884a03
 #include "futils.hpp"
c884a03
 #include "types.hpp"
c884a03
+#include "safe_op.hpp"
c884a03
c884a03
 // + standard includes
c884a03
 #include <string>
c884a03
@@ -269,8 +270,9 @@ namespace Exiv2
c884a03
                             std::cout << "Exiv2::Jp2Image::readMetadata: "
c884a03
                                      << "Color data found" << std::endl;
c884a03
 #endif
c884a03
+
c884a03
                             long pad = 3 ; // 3 padding bytes 2 0 0
c884a03
-                            DataBuf data(subBox.length+8);
c884a03
+                            DataBuf data(Safe::add(subBox.length, static_cast<uint32_t>(8)));
c884a03
                             io_->read(data.pData_,data.size_);
c884a03
                             long    iccLength = getULong(data.pData_+pad, bigEndian);
c884a03
                             DataBuf icc(iccLength);
c884a03
diff --git a/src/safe_op.hpp b/src/safe_op.hpp
c884a03
new file mode 100644
c884a03
index 0000000..014b7f3
c884a03
--- /dev/null
c884a03
+++ b/src/safe_op.hpp
c884a03
@@ -0,0 +1,310 @@
c884a03
+// ********************************************************* -*- C++ -*-
c884a03
+/*
c884a03
+ * Copyright (C) 2004-2017 Exiv2 maintainers
c884a03
+ *
c884a03
+ * This program is part of the Exiv2 distribution.
c884a03
+ *
c884a03
+ * This program is free software; you can redistribute it and/or
c884a03
+ * modify it under the terms of the GNU General Public License
c884a03
+ * as published by the Free Software Foundation; either version 2
c884a03
+ * of the License, or (at your option) any later version.
c884a03
+ *
c884a03
+ * This program is distributed in the hope that it will be useful,
c884a03
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
c884a03
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
c884a03
+ * GNU General Public License for more details.
c884a03
+ *
c884a03
+ * You should have received a copy of the GNU General Public License
c884a03
+ * along with this program; if not, write to the Free Software
c884a03
+ * Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
c884a03
+ */
c884a03
+/*!
c884a03
+  @file    safe_op.hpp
c884a03
+  @brief   Overflow checks for integers
c884a03
+  @author  Dan Čermák (D4N)
c884a03
+           dan.cermak@cgc-instruments.com
c884a03
+  @date    14-Dec-17, D4N: created
c884a03
+ */
c884a03
+
c884a03
+#ifndef SAFE_OP_HPP_
c884a03
+#define SAFE_OP_HPP_
c884a03
+
c884a03
+#include <limits>
c884a03
+#include <stdexcept>
c884a03
+
c884a03
+#ifdef _MSC_VER
c884a03
+#include <Intsafe.h>
c884a03
+#endif
c884a03
+
c884a03
+/*!
c884a03
+ * @brief Arithmetic operations with overflow checks
c884a03
+ */
c884a03
+namespace Safe
c884a03
+{
c884a03
+    /*!
c884a03
+     * @brief Helper structs for providing integer overflow checks.
c884a03
+     *
c884a03
+     * This namespace contains the internal helper structs fallback_add_overflow
c884a03
+     * and builtin_add_overflow. Both have a public static member function add
c884a03
+     * with the following interface:
c884a03
+     *
c884a03
+     * bool add(T summand_1, T summand_2, T& result)
c884a03
+     *
c884a03
+     * where T is the type over which the struct is templated.
c884a03
+     *
c884a03
+     * The function performs a check whether the addition summand_1 + summand_2
c884a03
+     * can be performed without an overflow. If the operation would overflow,
c884a03
+     * true is returned and the addition is not performed if it would result in
c884a03
+     * undefined behavior. If no overflow occurs, the sum is saved in result and
c884a03
+     * false is returned.
c884a03
+     *
c884a03
+     * fallback_add_overflow implements a portable but slower overflow check.
c884a03
+     * builtin_add_overflow uses compiler builtins (when available) and should
c884a03
+     * be considerably faster. As builtins are not available for all types,
c884a03
+     * builtin_add_overflow falls back to fallback_add_overflow when no builtin
c884a03
+     * is available.
c884a03
+     */
c884a03
+    namespace Internal
c884a03
+    {
c884a03
+        /*!
c884a03
+         * @brief Helper struct to determine whether a type is signed or unsigned
c884a03
+
c884a03
+         * This struct is a backport of std::is_signed from C++11. It has a public
c884a03
+         * enum with the property VALUE which is true when the type is signed or
c884a03
+         * false if it is unsigned.
c884a03
+         */
c884a03
+        template <typename T>
c884a03
+        struct is_signed
c884a03
+        {
c884a03
+            enum
c884a03
+            {
c884a03
+                VALUE = T(-1) < T(0)
c884a03
+            };
c884a03
+        };
c884a03
+
c884a03
+        /*!
c884a03
+         * @brief Helper struct for SFINAE, from C++11
c884a03
+
c884a03
+         * This struct has a public typedef called type typedef'd to T if B is
c884a03
+         * true. Otherwise there is no typedef.
c884a03
+         */
c884a03
+        template <bool B, class T = void>
c884a03
+        struct enable_if
c884a03
+        {
c884a03
+        };
c884a03
+
c884a03
+        /*!
c884a03
+         * @brief Specialization of enable_if for the case B == true
c884a03
+         */
c884a03
+        template <class T>
c884a03
+        struct enable_if<true, T>
c884a03
+        {
c884a03
+            typedef T type;
c884a03
+        };
c884a03
+
c884a03
+        /*!
c884a03
+         * @brief Fallback overflow checker, specialized via SFINAE
c884a03
+         *
c884a03
+         * This struct implements a 'fallback' addition with an overflow check,
c884a03
+         * i.e. it does not rely on compiler intrinsics.  It is specialized via
c884a03
+         * SFINAE for signed and unsigned integer types and provides a public
c884a03
+         * static member function add.
c884a03
+         */
c884a03
+        template <typename T, typename = void>
c884a03
+        struct fallback_add_overflow;
c884a03
+
c884a03
+        /*!
c884a03
+         * @brief Overload of fallback_add_overflow for signed integers
c884a03
+         */
c884a03
+        template <typename T>
c884a03
+        struct fallback_add_overflow<T, typename enable_if<is_signed<T>::VALUE>::type>
c884a03
+        {
c884a03
+            /*!
c884a03
+             * @brief Adds the two summands only if no overflow occurs
c884a03
+             *
c884a03
+             * This function performs a check if summand_1 + summand_2 would
c884a03
+             * overflow and returns true in that case. If no overflow occurs,
c884a03
+             * the sum is saved in result and false is returned.
c884a03
+             *
c884a03
+             * @return true on overflow, false on no overflow
c884a03
+             *
c884a03
+             * The check for an overflow is performed before the addition to
c884a03
+             * ensure that no undefined behavior occurs. The value in result is
c884a03
+             * only valid when the function returns false.
c884a03
+             *
c884a03
+             * Further information:
c884a03
+             * https://wiki.sei.cmu.edu/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow
c884a03
+             */
c884a03
+            static bool add(T summand_1, T summand_2, T& result)
c884a03
+            {
c884a03
+                if (((summand_2 >= 0) && (summand_1 > std::numeric_limits<T>::max() - summand_2)) ||
c884a03
+                    ((summand_2 < 0) && (summand_1 < std::numeric_limits<T>::min() - summand_2))) {
c884a03
+                    return true;
c884a03
+                } else {
c884a03
+                    result = summand_1 + summand_2;
c884a03
+                    return false;
c884a03
+                }
c884a03
+            }
c884a03
+        };
c884a03
+
c884a03
+        /*!
c884a03
+         * @brief Overload of fallback_add_overflow for unsigned integers
c884a03
+         */
c884a03
+        template <typename T>
c884a03
+        struct fallback_add_overflow<T, typename enable_if<!is_signed<T>::VALUE>::type>
c884a03
+        {
c884a03
+            /*!
c884a03
+             * @brief Adds the two summands only if no overflow occurs
c884a03
+             *
c884a03
+             * This function performs a check if summand_1 + summand_2 would
c884a03
+             * overflow and returns true in that case. If no overflow occurs,
c884a03
+             * the sum is saved in result and false is returned.
c884a03
+             *
c884a03
+             * @return true on overflow, false on no overflow
c884a03
+             *
c884a03
+             * Further information:
c884a03
+             * https://wiki.sei.cmu.edu/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap
c884a03
+             */
c884a03
+            static bool add(T summand_1, T summand_2, T& result)
c884a03
+            {
c884a03
+                if (summand_1 > std::numeric_limits<T>::max() - summand_2) {
c884a03
+                    return true;
c884a03
+                } else {
c884a03
+                    result = summand_1 + summand_2;
c884a03
+                    return false;
c884a03
+                }
c884a03
+            }
c884a03
+        };
c884a03
+
c884a03
+        /*!
c884a03
+         * @brief Overflow checker using compiler intrinsics
c884a03
+         *
c884a03
+         * This struct provides an add function with the same interface &
c884a03
+         * behavior as fallback_add_overload::add but it relies on compiler
c884a03
+         * intrinsics instead. This version should be considerably faster than
c884a03
+         * the fallback version as it can fully utilize available CPU
c884a03
+         * instructions & the compiler's diagnostic.
c884a03
+         *
c884a03
+         * However, as some compilers don't provide intrinsics for certain
c884a03
+         * types, the default implementation of add is the version from falback.
c884a03
+         *
c884a03
+         * The struct is explicitly specialized for each type via #ifdefs for
c884a03
+         * each compiler.
c884a03
+         */
c884a03
+        template <typename T>
c884a03
+        struct builtin_add_overflow
c884a03
+        {
c884a03
+            /*!
c884a03
+             * @brief Add summand_1 and summand_2 and check for overflows.
c884a03
+             *
c884a03
+             * This is the default add() function that uses
c884a03
+             * fallback_add_overflow<T>::add(). All specializations must have
c884a03
+             * exactly the same interface and behave the same way.
c884a03
+             */
c884a03
+            static inline bool add(T summand_1, T summand_2, T& result)
c884a03
+            {
c884a03
+                return fallback_add_overflow<T>::add(summand_1, summand_2, result);
c884a03
+            }
c884a03
+        };
c884a03
+
c884a03
+#if defined(__GNUC__) || defined(__clang__)
c884a03
+#if __GNUC__ >= 5
c884a03
+
c884a03
+/*!
c884a03
+ * This macro pastes a specialization of builtin_add_overflow using gcc's &
c884a03
+ * clang's __builtin_(s/u)add(l)(l)_overlow()
c884a03
+ *
c884a03
+ * The add function is implemented by forwarding the parameters to the intrinsic
c884a03
+ * and returning its value.
c884a03
+ *
c884a03
+ * The intrinsics are documented here:
c884a03
+ * https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html#Integer-Overflow-Builtins
c884a03
+ */
c884a03
+#define SPECIALIZE_builtin_add_overflow(type, builtin_name)                  \
c884a03
+    template <>                                                              \
c884a03
+    struct builtin_add_overflow<type>                                        \
c884a03
+    {                                                                        \
c884a03
+        static inline bool add(type summand_1, type summand_2, type& result) \
c884a03
+        {                                                                    \
c884a03
+            return builtin_name(summand_1, summand_2, &result);              \
c884a03
+        }                                                                    \
c884a03
+    }
c884a03
+
c884a03
+        SPECIALIZE_builtin_add_overflow(int, __builtin_sadd_overflow);
c884a03
+        SPECIALIZE_builtin_add_overflow(long, __builtin_saddl_overflow);
c884a03
+        SPECIALIZE_builtin_add_overflow(long long, __builtin_saddll_overflow);
c884a03
+
c884a03
+        SPECIALIZE_builtin_add_overflow(unsigned int, __builtin_uadd_overflow);
c884a03
+        SPECIALIZE_builtin_add_overflow(unsigned long, __builtin_uaddl_overflow);
c884a03
+        SPECIALIZE_builtin_add_overflow(unsigned long long, __builtin_uaddll_overflow);
c884a03
+
c884a03
+#undef SPECIALIZE_builtin_add_overflow
c884a03
+#endif
c884a03
+
c884a03
+#elif defined(_MSC_VER)
c884a03
+
c884a03
+/*!
c884a03
+ * This macro pastes a specialization of builtin_add_overflow using MSVC's
c884a03
+ * U(Int/Long/LongLong)Add.
c884a03
+ *
c884a03
+ * The add function is implemented by forwarding the parameters to the
c884a03
+ * intrinsic. As MSVC's intrinsics return S_OK on success, this specialization
c884a03
+ * returns whether the intrinsics return value does not equal S_OK. This ensures
c884a03
+ * a uniform interface of the add function (false is returned when no overflow
c884a03
+ * occurs, true on overflow).
c884a03
+ *
c884a03
+ * The intrinsics are documented here:
c884a03
+ * https://msdn.microsoft.com/en-us/library/windows/desktop/ff516460(v=vs.85).aspx
c884a03
+ */
c884a03
+#define SPECIALIZE_builtin_add_overflow_WIN(type, builtin_name)              \
c884a03
+    template <>                                                              \
c884a03
+    struct builtin_add_overflow<type>                                        \
c884a03
+    {                                                                        \
c884a03
+        static inline bool add(type summand_1, type summand_2, type& result) \
c884a03
+        {                                                                    \
c884a03
+            return builtin_name(summand_1, summand_2, &result) != S_OK;      \
c884a03
+        }                                                                    \
c884a03
+    }
c884a03
+
c884a03
+        SPECIALIZE_builtin_add_overflow_WIN(unsigned int, UIntAdd);
c884a03
+        SPECIALIZE_builtin_add_overflow_WIN(unsigned long, ULongAdd);
c884a03
+        SPECIALIZE_builtin_add_overflow_WIN(unsigned long long, ULongLongAdd);
c884a03
+
c884a03
+#undef SPECIALIZE_builtin_add_overflow_WIN
c884a03
+
c884a03
+#endif
c884a03
+
c884a03
+    }  // namespace Internal
c884a03
+
c884a03
+    /*!
c884a03
+     * @brief Safe addition, throws an exception on overflow.
c884a03
+     *
c884a03
+     * This function returns the result of summand_1 and summand_2 only when the
c884a03
+     * operation would not overflow, otherwise an exception of type
c884a03
+     * std::overflow_error is thrown.
c884a03
+     *
c884a03
+     * @param[in] summand_1, summand_2  summands to be summed up
c884a03
+     * @return  the sum of summand_1 and summand_2
c884a03
+     * @throws  std::overflow_error if the addition would overflow
c884a03
+     *
c884a03
+     * This function utilizes compiler builtins when available and should have a
c884a03
+     * very small performance hit then. When builtins are unavailable, a more
c884a03
+     * extensive check is required.
c884a03
+     *
c884a03
+     * Builtins are available for the following configurations:
c884a03
+     * - GCC/Clang for signed and unsigned int, long and long long (not char & short)
c884a03
+     * - MSVC for unsigned int, long and long long
c884a03
+     */
c884a03
+    template <typename T>
c884a03
+    T add(T summand_1, T summand_2)
c884a03
+    {
c884a03
+        T res = 0;
c884a03
+        if (Internal::builtin_add_overflow<T>::add(summand_1, summand_2, res)) {
c884a03
+            throw std::overflow_error("Overflow in addition");
c884a03
+        }
c884a03
+        return res;
c884a03
+    }
c884a03
+
c884a03
+}  // namespace Safe
c884a03
+
c884a03
+#endif  // SAFE_OP_HPP_