SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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 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
 
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
 
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
 

Similaire à 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 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
 
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
 
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
 

Dernier

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 

Dernier (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 

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