[esnacc-dev] cxx-lib/asn-stringtype: Fix a bad shift

Message ID 20180115204222.11690-1-aconole@bytheb.org
State Accepted
Delegated to: Aaron Conole
Headers show

Commit Message

Aaron Conole Jan. 15, 2018, 8:42 p.m.
Under some conditions, it is possible for undefined behavior to be
invoked in the asn-string deterpret, if the bit-shift value would
equal or exceed sizeof(char)*8.  Rewrite the routine to be a bit
more efficient and to fix this potential undefine behavior.

Signed-off-by: Aaron Conole <aconole@bytheb.org>
---
 cxx-lib/src/asn-stringtype.cpp | 60 ++++++++++++++++++++----------------------
 1 file changed, 28 insertions(+), 32 deletions(-)

Patch

diff --git a/cxx-lib/src/asn-stringtype.cpp b/cxx-lib/src/asn-stringtype.cpp
index 4179b8b..e1efc0d 100644
--- a/cxx-lib/src/asn-stringtype.cpp
+++ b/cxx-lib/src/asn-stringtype.cpp
@@ -354,44 +354,40 @@  AsnString& AsnString::operator=(const char* str)
 
 void AsnString::Deterpret(AsnBufBits &b, AsnLen &bitsDecoded, long)
 {
-	AsnLen len;
-	int B = numBits();
-	int B2 = findB2(B);
-	int count = 0;
-	bool bNotFound = true;
+    AsnLen len = numBits();
+    int count = 0;
+
+    if (b.IsAligned())
+        len = findB2(len);
+
     int sizePermittedAlpha;
     const char* permittedAlphabet = PermittedAlphabet(sizePermittedAlpha);
-	int ub = (int)permittedAlphabet[sizePermittedAlpha - 1];
-	
-	if(b.IsAligned())
-		len = B2;
-	else
-		len = B;
+    int ub = (int) permittedAlphabet[sizePermittedAlpha - 1];
 
-	if(ub <= ((1 << len) - 1) )
-	{
-		len = (sizeof(char) * 8);
-	}
+    if (ub <= ((1 << len) - 1)) {
+        len = (sizeof(char) * 8);
+    }
 
-	unsigned char* seg = b.GetBits(len);
+    unsigned char* seg = b.GetBits(len);
     bitsDecoded += len;
-	seg[0] >>= ((sizeof(char)*8) - len);
-	
-	
-	if(!(ub <= ((1 << len) - 1)) )
-	{
-		while(bNotFound)
-		{
-			if(count == (int)seg[0])
-			{
-				seg[0] = permittedAlphabet[count];
-				bNotFound = false;
-			}
-			count++;
-		}
-	}
+    if (len <= ((sizeof(char) * 8) - 1))
+        seg[0] >>= ((sizeof(char)*8) - len);
+    else
+        seg[0] = 0;
+
+    if (!(ub <= ((1 << len) - 1))) {
+        bool bNotFound = true;
+
+        while (bNotFound) {
+            if (count == (int)seg[0]) {
+                seg[0] = permittedAlphabet[count];
+                bNotFound = false;
+            }
+            count++;
+        }
+    }
 
-	putChar((char*)seg);
+    putChar((char*)seg);
     delete [] seg;
 }