SlideShare una empresa de Scribd logo
1 de 5
Descargar para leer sin conexión
Lesson 11. Pattern 3. Shift operations
It is easy to make a mistake in code that works with separate bits. The pattern of 64-bit errors under
consideration relates to shift operations. Here is an example of code:

ptrdiff_t SetBitN(ptrdiff_t value, unsigned bitNum) {

    ptrdiff_t mask = 1 << bitNum;

    return value | mask;

}

This code works well on a 32-bit architecture and allows you to set a bit with numbers from 0 to 31 into
one. After porting the program to a 64-bit platform you need to set bits from 0 to 63. But this code will
never set the bits with the numbers 32-63. Note that the numerical literal "1" has int type and causes an
overflow when a shift in 32 positions occurs as shown in Figure 1. As a result, we will get 0 (Figure 1-B)
or 1 (Figure 1-C) depending on the compiler implementation.




 Figure 1 - a) Correct setting of the 31-st bit in a 32-bit code; b,c) - Incorrect setting of the 32-nd bit on a
                                   64-bit system (two variants of behavior)

To correct the code we must make the type of the constant "1" the same as that of mask variable:

ptrdiff_t mask = ptrdiff_t(1) << bitNum;
Note also that the non-corrected code will lead to one more interesting error. When setting the 31-st bit
on a 64-bit system, the function's result will be the value 0xffffffff80000000 (see Figure 2). The result of
the expression 1 << 31 is the negative number -2147483648. This number is presented in a 64-bit
integer variable as 0xffffffff80000000.




                      Figure 2 - The error of setting the 31-st bit on a 64-bit system.

You should remember and take into consideration the effects of shifting values of different types. To
better understand all said above, consider some interesting expressions with shifts in a 64-bit system
shown in Table 1.




 Table 1 - Expressions with shifts and their results in a 64-bit system (we used Visual C++ 2005 compiler)

The type of errors we have described is considered dangerous not only from the viewpoint of program
operation correctness but from the viewpoint of security as well. Potentially, by manipulating with the
input data of such incorrect functions one can get inadmissible rights when, for example, dealing with
processing of access permissions' masks defined by separate bits. Questions related to exploiting errors
in 64-bit code for application cracking and compromise are described in the article "Safety of 64-bit
code".

Now a subtler example:

struct BitFieldStruct {

   unsigned short a:15;

   unsigned short b:13;

};

BitFieldStruct obj;

obj.a = 0x4000;

size_t addr = obj.a << 17; //Sign Extension
printf("addr 0x%Ixn", addr);

//Output on 32-bit system: 0x80000000

//Output on 64-bit system: 0xffffffff80000000

In the 32-bit environment, the order of calculating the expression will be as shown in Figure 3.




                            Figure 3 - Calculation of expression in 32-bit code

Note that a sign extension of "unsigned short" type to "signed int" takes place when calculating "obj.a
<< 17". To make it clear, consider the following code:

#include <stdio.h>

template <typename T> void PrintType(T)

{

    printf("type is %s %d-bitn",

               (T)-1 < 0 ? "signed" : "unsigned", sizeof(T)*8);

}

struct BitFieldStruct {

    unsigned short a:15;

    unsigned short b:13;

};

int main(void)
{

    BitFieldStruct bf;

    PrintType( bf.a );

    PrintType( bf.a << 2);

    return 0;

}

Result:

type is unsigned 16-bit

type is signed 32-bit

Now let us see the consequence of the sign extension in a 64-bit code. The sequence of calculating the
expression is shown in Figure 4.




                             Figure 4 - Calculation of expression in 64-bit code

The member of "obj.a" structure is converted from the bit field of "unsigned short" type to "int". "obj.a
<< 17" expression has "int" type but it is converted to ptrdiff_t and then to size_t before it is assigned to
addr variable. As a result, we will get the value 0xffffffff80000000 instead of 0x0000000080000000
expected.
Be careful when working with bit fields. To avoid the situation described in our example we need only to
explicitly convert "obj.a" to size_t type.

...

size_t addr = size_t(obj.a) << 17;

printf("addr 0x%Ixn", addr);

//Output on 32-bit system: 0x80000000

//Output on 64-bit system: 0x80000000


Diagnosis
Potentially unsafe shifts are detected by PVS-Studio static analyzer when it detects an implicit extension
of a 32-bit type to memsize type. The analyzer will warn you about the unsafe construct with the
diagnostic warning V101. The shift operation is not suspicious by itself. But the analyzer detects an
implicit extension of int type to memsize type when it is assigned to a variable, and informs the
programmer about it to check the code fragment that may contain an error. Correspondingly, when
there is no extension, the analyzer considers the code safe. For example: "int mask = 1 << bitNum;".

The course authors: Andrey Karpov (karpov@viva64.com), Evgeniy Ryzhkov (evg@viva64.com).

The rightholder of the course "Lessons on development of 64-bit C/C++ applications" is OOO "Program
Verification Systems". The company develops software in the sphere of source program code analysis.
The company's site: http://www.viva64.com.

Contacts: e-mail: support@viva64.com, Tula, 300027, PO box 1800

Más contenido relacionado

La actualidad más candente

1 arithmetic
1 arithmetic1 arithmetic
1 arithmeticfyjordan9
 
C bitwise operators
C bitwise operatorsC bitwise operators
C bitwise operatorsSuneel Dogra
 
Calculating the hamming code
Calculating the hamming codeCalculating the hamming code
Calculating the hamming codeUmesh Gupta
 
Module 00 Bitwise Operators in C
Module 00 Bitwise Operators in CModule 00 Bitwise Operators in C
Module 00 Bitwise Operators in CTushar B Kute
 
Manoch1raw 160512091436
Manoch1raw 160512091436Manoch1raw 160512091436
Manoch1raw 160512091436marangburu42
 
Error detection and correction codes
Error detection and correction codesError detection and correction codes
Error detection and correction codesGargiKhanna1
 
FPGA Based Decimal Matrix Code for Passive RFID Tag
FPGA Based Decimal Matrix Code for Passive RFID TagFPGA Based Decimal Matrix Code for Passive RFID Tag
FPGA Based Decimal Matrix Code for Passive RFID TagIJERA Editor
 
Comparison of analyzers' diagnostic possibilities at checking 64-bit code
Comparison of analyzers' diagnostic possibilities at checking 64-bit codeComparison of analyzers' diagnostic possibilities at checking 64-bit code
Comparison of analyzers' diagnostic possibilities at checking 64-bit codePVS-Studio
 
Floating Point Representation premium.pptx
Floating Point Representation premium.pptxFloating Point Representation premium.pptx
Floating Point Representation premium.pptxshomikishpa
 
digital logic circuits, digital component floting and fixed point
 digital logic circuits, digital component floting and fixed point digital logic circuits, digital component floting and fixed point
digital logic circuits, digital component floting and fixed pointRai University
 
Lecture 1: basic syntax
Lecture 1: basic syntaxLecture 1: basic syntax
Lecture 1: basic syntaxVivek Bhargav
 

La actualidad más candente (20)

1 arithmetic
1 arithmetic1 arithmetic
1 arithmetic
 
C bitwise operators
C bitwise operatorsC bitwise operators
C bitwise operators
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
15 bitwise operators
15 bitwise operators15 bitwise operators
15 bitwise operators
 
Calculating the hamming code
Calculating the hamming codeCalculating the hamming code
Calculating the hamming code
 
Module 00 Bitwise Operators in C
Module 00 Bitwise Operators in CModule 00 Bitwise Operators in C
Module 00 Bitwise Operators in C
 
Manoch1raw 160512091436
Manoch1raw 160512091436Manoch1raw 160512091436
Manoch1raw 160512091436
 
Assignment
AssignmentAssignment
Assignment
 
Matlab numbers
Matlab numbersMatlab numbers
Matlab numbers
 
Bitwise operators
Bitwise operatorsBitwise operators
Bitwise operators
 
Error detection and correction codes
Error detection and correction codesError detection and correction codes
Error detection and correction codes
 
Cin and cout
Cin and coutCin and cout
Cin and cout
 
FPGA Based Decimal Matrix Code for Passive RFID Tag
FPGA Based Decimal Matrix Code for Passive RFID TagFPGA Based Decimal Matrix Code for Passive RFID Tag
FPGA Based Decimal Matrix Code for Passive RFID Tag
 
Comparison of analyzers' diagnostic possibilities at checking 64-bit code
Comparison of analyzers' diagnostic possibilities at checking 64-bit codeComparison of analyzers' diagnostic possibilities at checking 64-bit code
Comparison of analyzers' diagnostic possibilities at checking 64-bit code
 
vhdl exp-5
vhdl exp-5vhdl exp-5
vhdl exp-5
 
Floating Point Representation premium.pptx
Floating Point Representation premium.pptxFloating Point Representation premium.pptx
Floating Point Representation premium.pptx
 
digital logic circuits, digital component floting and fixed point
 digital logic circuits, digital component floting and fixed point digital logic circuits, digital component floting and fixed point
digital logic circuits, digital component floting and fixed point
 
Hamming code system
Hamming code systemHamming code system
Hamming code system
 
Lecture 1: basic syntax
Lecture 1: basic syntaxLecture 1: basic syntax
Lecture 1: basic syntax
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 

Destacado

Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging ChallengesAaron Irizarry
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesNed Potter
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsLinkedIn
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with DataSeth Familian
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Destacado (7)

Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging Challenges
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and Archives
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with Data
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar a Lesson 11. Pattern 3. Shift operations

Lesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbersLesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbersPVS-Studio
 
About size_t and ptrdiff_t
About size_t and ptrdiff_tAbout size_t and ptrdiff_t
About size_t and ptrdiff_tPVS-Studio
 
International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)IJERD Editor
 
Gsp 215 Future Our Mission/newtonhelp.com
Gsp 215 Future Our Mission/newtonhelp.comGsp 215 Future Our Mission/newtonhelp.com
Gsp 215 Future Our Mission/newtonhelp.comamaranthbeg8
 
GSP 215 Doing by learn/newtonhelp.com
GSP 215 Doing by learn/newtonhelp.comGSP 215 Doing by learn/newtonhelp.com
GSP 215 Doing by learn/newtonhelp.combellflower126
 
GSP 215 Become Exceptional/newtonhelp.com
GSP 215 Become Exceptional/newtonhelp.comGSP 215 Become Exceptional/newtonhelp.com
GSP 215 Become Exceptional/newtonhelp.combellflower148
 
GSP 215 Perfect Education/newtonhelp.com
GSP 215 Perfect Education/newtonhelp.comGSP 215 Perfect Education/newtonhelp.com
GSP 215 Perfect Education/newtonhelp.combellflower169
 
Bitwise Operations(1).pdf
Bitwise Operations(1).pdfBitwise Operations(1).pdf
Bitwise Operations(1).pdfDalvinCalvin
 
A collection of examples of 64 bit errors in real programs
A collection of examples of 64 bit errors in real programsA collection of examples of 64 bit errors in real programs
A collection of examples of 64 bit errors in real programsMichael Scovetta
 
Write the code in C, here is the template providedThe input used .pdf
Write the code in C, here is the template providedThe input used .pdfWrite the code in C, here is the template providedThe input used .pdf
Write the code in C, here is the template providedThe input used .pdfsales223546
 
Chapter 5: Cominational Logic with MSI and LSI
Chapter 5: Cominational Logic with MSI and LSIChapter 5: Cominational Logic with MSI and LSI
Chapter 5: Cominational Logic with MSI and LSIEr. Nawaraj Bhandari
 
C Programming Language
C Programming LanguageC Programming Language
C Programming LanguageRTS Tech
 
Customizable Microprocessor design on Nexys 3 Spartan FPGA Board
Customizable Microprocessor design on Nexys 3 Spartan FPGA BoardCustomizable Microprocessor design on Nexys 3 Spartan FPGA Board
Customizable Microprocessor design on Nexys 3 Spartan FPGA BoardBharat Biyani
 
20 issues of porting C++ code on the 64-bit platform
20 issues of porting C++ code on the 64-bit platform20 issues of porting C++ code on the 64-bit platform
20 issues of porting C++ code on the 64-bit platformPVS-Studio
 
Program errors occurring while porting C++ code from 32-bit platforms on 64-b...
Program errors occurring while porting C++ code from 32-bit platforms on 64-b...Program errors occurring while porting C++ code from 32-bit platforms on 64-b...
Program errors occurring while porting C++ code from 32-bit platforms on 64-b...Andrey Karpov
 
20 issues of porting C++ code on the 64-bit platform
20 issues of porting C++ code on the 64-bit platform20 issues of porting C++ code on the 64-bit platform
20 issues of porting C++ code on the 64-bit platformAndrey Karpov
 

Similar a Lesson 11. Pattern 3. Shift operations (20)

Lesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbersLesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbers
 
C programming part2
C programming part2C programming part2
C programming part2
 
C programming part2
C programming part2C programming part2
C programming part2
 
C programming part2
C programming part2C programming part2
C programming part2
 
About size_t and ptrdiff_t
About size_t and ptrdiff_tAbout size_t and ptrdiff_t
About size_t and ptrdiff_t
 
International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)
 
Gsp 215 Future Our Mission/newtonhelp.com
Gsp 215 Future Our Mission/newtonhelp.comGsp 215 Future Our Mission/newtonhelp.com
Gsp 215 Future Our Mission/newtonhelp.com
 
GSP 215 Doing by learn/newtonhelp.com
GSP 215 Doing by learn/newtonhelp.comGSP 215 Doing by learn/newtonhelp.com
GSP 215 Doing by learn/newtonhelp.com
 
GSP 215 Become Exceptional/newtonhelp.com
GSP 215 Become Exceptional/newtonhelp.comGSP 215 Become Exceptional/newtonhelp.com
GSP 215 Become Exceptional/newtonhelp.com
 
GSP 215 Perfect Education/newtonhelp.com
GSP 215 Perfect Education/newtonhelp.comGSP 215 Perfect Education/newtonhelp.com
GSP 215 Perfect Education/newtonhelp.com
 
Bitwise Operations(1).pdf
Bitwise Operations(1).pdfBitwise Operations(1).pdf
Bitwise Operations(1).pdf
 
A collection of examples of 64 bit errors in real programs
A collection of examples of 64 bit errors in real programsA collection of examples of 64 bit errors in real programs
A collection of examples of 64 bit errors in real programs
 
Write the code in C, here is the template providedThe input used .pdf
Write the code in C, here is the template providedThe input used .pdfWrite the code in C, here is the template providedThe input used .pdf
Write the code in C, here is the template providedThe input used .pdf
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 
Chapter 5: Cominational Logic with MSI and LSI
Chapter 5: Cominational Logic with MSI and LSIChapter 5: Cominational Logic with MSI and LSI
Chapter 5: Cominational Logic with MSI and LSI
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
 
Customizable Microprocessor design on Nexys 3 Spartan FPGA Board
Customizable Microprocessor design on Nexys 3 Spartan FPGA BoardCustomizable Microprocessor design on Nexys 3 Spartan FPGA Board
Customizable Microprocessor design on Nexys 3 Spartan FPGA Board
 
20 issues of porting C++ code on the 64-bit platform
20 issues of porting C++ code on the 64-bit platform20 issues of porting C++ code on the 64-bit platform
20 issues of porting C++ code on the 64-bit platform
 
Program errors occurring while porting C++ code from 32-bit platforms on 64-b...
Program errors occurring while porting C++ code from 32-bit platforms on 64-b...Program errors occurring while porting C++ code from 32-bit platforms on 64-b...
Program errors occurring while porting C++ code from 32-bit platforms on 64-b...
 
20 issues of porting C++ code on the 64-bit platform
20 issues of porting C++ code on the 64-bit platform20 issues of porting C++ code on the 64-bit platform
20 issues of porting C++ code on the 64-bit platform
 

Último

Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Último (20)

Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Lesson 11. Pattern 3. Shift operations

  • 1. Lesson 11. Pattern 3. Shift operations It is easy to make a mistake in code that works with separate bits. The pattern of 64-bit errors under consideration relates to shift operations. Here is an example of code: ptrdiff_t SetBitN(ptrdiff_t value, unsigned bitNum) { ptrdiff_t mask = 1 << bitNum; return value | mask; } This code works well on a 32-bit architecture and allows you to set a bit with numbers from 0 to 31 into one. After porting the program to a 64-bit platform you need to set bits from 0 to 63. But this code will never set the bits with the numbers 32-63. Note that the numerical literal "1" has int type and causes an overflow when a shift in 32 positions occurs as shown in Figure 1. As a result, we will get 0 (Figure 1-B) or 1 (Figure 1-C) depending on the compiler implementation. Figure 1 - a) Correct setting of the 31-st bit in a 32-bit code; b,c) - Incorrect setting of the 32-nd bit on a 64-bit system (two variants of behavior) To correct the code we must make the type of the constant "1" the same as that of mask variable: ptrdiff_t mask = ptrdiff_t(1) << bitNum;
  • 2. Note also that the non-corrected code will lead to one more interesting error. When setting the 31-st bit on a 64-bit system, the function's result will be the value 0xffffffff80000000 (see Figure 2). The result of the expression 1 << 31 is the negative number -2147483648. This number is presented in a 64-bit integer variable as 0xffffffff80000000. Figure 2 - The error of setting the 31-st bit on a 64-bit system. You should remember and take into consideration the effects of shifting values of different types. To better understand all said above, consider some interesting expressions with shifts in a 64-bit system shown in Table 1. Table 1 - Expressions with shifts and their results in a 64-bit system (we used Visual C++ 2005 compiler) The type of errors we have described is considered dangerous not only from the viewpoint of program operation correctness but from the viewpoint of security as well. Potentially, by manipulating with the input data of such incorrect functions one can get inadmissible rights when, for example, dealing with processing of access permissions' masks defined by separate bits. Questions related to exploiting errors in 64-bit code for application cracking and compromise are described in the article "Safety of 64-bit code". Now a subtler example: struct BitFieldStruct { unsigned short a:15; unsigned short b:13; }; BitFieldStruct obj; obj.a = 0x4000; size_t addr = obj.a << 17; //Sign Extension
  • 3. printf("addr 0x%Ixn", addr); //Output on 32-bit system: 0x80000000 //Output on 64-bit system: 0xffffffff80000000 In the 32-bit environment, the order of calculating the expression will be as shown in Figure 3. Figure 3 - Calculation of expression in 32-bit code Note that a sign extension of "unsigned short" type to "signed int" takes place when calculating "obj.a << 17". To make it clear, consider the following code: #include <stdio.h> template <typename T> void PrintType(T) { printf("type is %s %d-bitn", (T)-1 < 0 ? "signed" : "unsigned", sizeof(T)*8); } struct BitFieldStruct { unsigned short a:15; unsigned short b:13; }; int main(void)
  • 4. { BitFieldStruct bf; PrintType( bf.a ); PrintType( bf.a << 2); return 0; } Result: type is unsigned 16-bit type is signed 32-bit Now let us see the consequence of the sign extension in a 64-bit code. The sequence of calculating the expression is shown in Figure 4. Figure 4 - Calculation of expression in 64-bit code The member of "obj.a" structure is converted from the bit field of "unsigned short" type to "int". "obj.a << 17" expression has "int" type but it is converted to ptrdiff_t and then to size_t before it is assigned to addr variable. As a result, we will get the value 0xffffffff80000000 instead of 0x0000000080000000 expected.
  • 5. Be careful when working with bit fields. To avoid the situation described in our example we need only to explicitly convert "obj.a" to size_t type. ... size_t addr = size_t(obj.a) << 17; printf("addr 0x%Ixn", addr); //Output on 32-bit system: 0x80000000 //Output on 64-bit system: 0x80000000 Diagnosis Potentially unsafe shifts are detected by PVS-Studio static analyzer when it detects an implicit extension of a 32-bit type to memsize type. The analyzer will warn you about the unsafe construct with the diagnostic warning V101. The shift operation is not suspicious by itself. But the analyzer detects an implicit extension of int type to memsize type when it is assigned to a variable, and informs the programmer about it to check the code fragment that may contain an error. Correspondingly, when there is no extension, the analyzer considers the code safe. For example: "int mask = 1 << bitNum;". The course authors: Andrey Karpov (karpov@viva64.com), Evgeniy Ryzhkov (evg@viva64.com). The rightholder of the course "Lessons on development of 64-bit C/C++ applications" is OOO "Program Verification Systems". The company develops software in the sphere of source program code analysis. The company's site: http://www.viva64.com. Contacts: e-mail: support@viva64.com, Tula, 300027, PO box 1800