From 91dfcd5a5d2cb20285504d787ee4a6135303891a Mon Sep 17 00:00:00 2001
From: Jan Breuer <jan.breuer@jaybee.cz>
Date: 周日, 15 5月 2016 20:01:44 +0800
Subject: [PATCH] Fix buffer overflow in SCPI_NumberToStr, SCPI_DoubleToStr and SCPI_FloatToStr

---
 libscpi/src/units.c |   24 +++++++++++++++---------
 1 files changed, 15 insertions(+), 9 deletions(-)

diff --git a/libscpi/src/units.c b/libscpi/src/units.c
index 47c7f9e..9fc2072 100644
--- a/libscpi/src/units.c
+++ b/libscpi/src/units.c
@@ -469,7 +469,7 @@
  * @param context
  * @param value number value
  * @param str target string
- * @param len max length of string
+ * @param len max length of string including null-character termination
  * @return number of chars written to string
  */
 size_t SCPI_NumberToStr(scpi_t * context, const scpi_choice_def_t * special, scpi_number_t * value, char * str, size_t len) {
@@ -477,28 +477,34 @@
     const char * unit;
     size_t result;
 
-    if (!value || !str) {
+    if (!value || !str || len==0) {
         return 0;
     }
 
     if (value->special) {
         if (SCPI_ChoiceToName(special, value->tag, &type)) {
             strncpy(str, type, len);
-            return min(strlen(type), len);
+            result = SCPIDEFINE_strnlen(str, len - 1);
+            str[result] = '\0';
+            return result;
         } else {
-            str[0] = 0;
+            str[0] = '\0';
             return 0;
         }
     }
 
     result = SCPI_DoubleToStr(value->value, str, len);
 
-    unit = translateUnitInverse(context->units, value->unit);
+    if (result + 1 < len) {
+        unit = translateUnitInverse(context->units, value->unit);
 
-    if (unit) {
-        strncat(str, " ", len);
-        strncat(str, unit, len);
-        result += strlen(unit) + 1;
+        if (unit) {
+            strncat(str, " ", len - result);
+            if (result + 2 < len) {
+                strncat(str, unit, len - result - 1);
+            }
+            result = strlen(str);
+        }
     }
 
     return result;

--
Gitblit v1.9.1