From patchwork Mon Jan 15 20:42:22 2018 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [esnacc-dev] cxx-lib/asn-stringtype: Fix a bad shift X-Patchwork-Submitter: Aaron Conole X-Patchwork-Id: 24 X-Patchwork-Delegate: aconole@bytheb.org Message-Id: <20180115204222.11690-1-aconole@bytheb.org> To: dev@lists.esnacc.org Date: Mon, 15 Jan 2018 15:42:22 -0500 From: Aaron Conole List-Id: eSNACC Development discussion 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 --- cxx-lib/src/asn-stringtype.cpp | 60 ++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 32 deletions(-) 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; }