DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • A Scalable Framework for Enterprise Salesforce Optimization: Turning Outcomes Into an Operating System
  • Performance Optimization Techniques in Flutter 3.41 for Mobile App Development
  • Stop Burning Money on AI Inference: A Cloud-Agnostic Guide to Serverless Cost Optimization
  • Why Image Optimization in Modern Applications Matters More Than You Think

Trending

  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • Rethinking Java CRUDs With Event Sourcing and CQRS Patterns
  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  • How to Format Articles for DZone
  1. DZone
  2. Software Design and Architecture
  3. Performance
  4. Troubleshooting a Crash Triggered by Clang Compiler Optimization

Troubleshooting a Crash Triggered by Clang Compiler Optimization

See where things can go wrong with Clang and how to fix it.

By 
Jamie Liu user avatar
Jamie Liu
·
Dec. 23, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
9.5K Views

Join the DZone community and get the full member experience.

Join For Free

If someone told you that the following C++ function would cause the program to crash, what would you think it is that caused the problem?

C++
 




xxxxxxxxxx
1


 
1
std::string b2s(bool b) {
2
    return b ? "true" : "false";
3
}



If you were given more descriptions, for example:

  • The crash reappears with a certain probability.
  • The error message shows Program terminated with signal SIGSEGV.
  • The backtrace information is usually incomplete or even missing.
  • When the optimization level is higher than -O2, the crash is more likely to happen.
  • The crash only happens while using Clang, but not GCC.

Well, some of the veterans may already have a clue. Here’s the minimal program that can reproduce the crash:

C++
 




xxxxxxxxxx
1
18


 
1
// file crash.cpp
2
#include <iostream>
3
#include <string>
4

          
5
std::string __attribute__((noinline)) b2s(bool b) {
6
    return b ? "true" : "false";
7
}
8

          
9
union {
10
    unsigned char c;
11
    bool b;
12
} volatile u;
13

          
14
int main() {
15
    u.c = 0x80;
16
    std::cout << b2s(u.b) << std::endl;
17
    return 0;
18
}



Shell
 




xxxxxxxxxx
1
25


 
1
$ clang++ -O2 crash.cpp
2
$ ./a.out
3
truefalse,d$x4DdzRx
4

          
5
Segmentation fault (core dumped)
6

          
7
$ gdb ./a.out core.3699
8
Core was generated by `./a.out'.
9
Program terminated with signal SIGSEGV, Segmentation fault.
10
#0  0x0000012cfffff0d4 in ?? ()
11
(gdb) bt
12
#0  0x0000012cfffff0d4 in ?? ()
13
#1  0x00000064fffff0f4 in ?? ()
14
#2  0x00000078fffff124 in ?? ()
15
#3  0x000000b4fffff1e4 in ?? ()
16
#4  0x000000fcfffff234 in ?? ()
17
#5  0x00000144fffff2f4 in ?? ()
18
#6  0x0000018cfffff364 in ?? ()
19
#7  0x0000000000000014 in ?? ()
20
#8  0x0110780100527a01 in ?? ()
21
#9  0x0000019008070c1b in ?? ()
22
#10 0x0000001c00000010 in ?? ()
23
#11 0x0000002ffffff088 in ?? ()
24
#12 0xe2ab001010074400 in ?? ()
25
#13 0x0000000000000000 in ?? ()



Though incomplete, the backtrace information still indicates that the program did not crash in the first place. In such a case, to quickly locate the first scene, let’s try AddressSanitizer (ASan).

Shell
 




xxxxxxxxxx
1
19


 
1
$ clang++ -g -O2 -fno-omit-frame-pointer -fsanitize=address crash.cpp
2
$ ./a.out
3
=================================================================
4
==3699==ERROR: AddressSanitizer: global-buffer-overflow on address 0x000000552805 at pc 0x0000004ff83a bp 0x7ffd7610d240 sp 0x7ffd7610c9f0
5
READ of size 133 at 0x000000552805 thread T0
6
    #0 0x4ff839 in __asan_memcpy (a.out+0x4ff839)
7
    #1 0x5390a7 in b2s[abi:cxx11](bool) crash.cpp:6
8
    #2 0x5391be in main crash.cpp:16:18
9
    #3 0x7faed604df42 in __libc_start_main (/usr/lib64/libc.so.6+0x23f42)
10
    #4 0x41c43d in _start (a.out+0x41c43d)
11

          
12
0x000000552805 is located 59 bytes to the left of global variable '<string literal>' defined in 'crash.cpp:6:25' (0x552840) of size 6
13
  '<string literal>' is ascii string 'false'
14
0x000000552805 is located 0 bytes to the right of global variable '<string literal>' defined in 'crash.cpp:6:16' (0x552800) of size 5
15
  '<string literal>' is ascii string 'true'
16
SUMMARY: AddressSanitizer: global-buffer-overflow (/home/dutor.hou/Wdir/nebula-graph/build/bug/a.out+0x4ff839) in __asan_memcpy
17
Shadow bytes around the buggy address:
18
…
19
...



From the information provided by ASan, we can see that global buffer overflow happened when the b2s(bool) function was reading the string constant true. Alright, let’s take a “God View” at the abnormal function and the program. It seems like we can get such a conclusion: Because the bool type parameter b of the b2s function was not initialized, the value stored in b is neither 0 nor 1[1], and that caused the problem. But here’s another question, why would such a value cause buffer overflow? If that interests you, change the type of b from bool to char or int and the problem will be fixed.

To answer the new question, we have to check what instructions does Clang++ generate from b2s. Before we do that, we should know:

  • In the sample program, the return value of b2s is a temporary std::string object, which is stored on the stack.
  • After C++ 11, GCC applies SBO (Small Buffer Optimization) by default on the implementation of std::string. The definition is something like this: std::string{ char *ptr; size_t size; union{ char buf[16]; size_t capacity}; }. For strings shorter than 16 bytes, no additional memory is required.

OK. Now let’s take a look at the disassembling of b2s. I added some key comments.

Plain Text
 




x
28


 
1
(gdb) disas b2s
2
Dump of assembler code for function b2s[abi:cxx11](bool):
3
   0x00401200 <+0>:     push   %r14
4
   0x00401202 <+2>:     push   %rbx
5
   0x00401203 <+3>:     push   %rax
6
   0x00401204 <+4>:     mov    %rdi,%r14         # Save the starting address of the return value (a string) in R14.
7
   0x00401207 <+7>:     mov    $0x402010,%ecx    # Save the starting address of "true" in ecx.
8
   0x0040120c <+12>:    mov    $0x402015,%eax    # Save the starting address of "false" in eax.
9
   0x00401211 <+17>:    test   %esi,%esi         # Test whether parameter b has a non-zero value.
10
   0x00401213 <+19>:    cmovne %rcx,%rax         # If b is not zero, save the address of "true" in rax.
11
   0x00401217 <+23>:    lea    0x10(%rdi),%rdi   # Save the starting address of buf in the string in rdi.
12
                                                 #  It is also the first parameter of memcpy.
13
   0x0040121b <+27>:    mov    %rdi,(%r14)       # Save rdi in the string's PTR  field, i.e., SBO.
14
   0x0040121e <+30>:    mov    %esi,%ebx         # Save the value of b in ebx.
15
   0x00401220 <+32>:    xor    $0x5,%rbx         # Calculate the XOR value of 0x5 and save it in rbx (i.e., ebx).
16
                                                 # Note that if rbx is 0 or 1, then the value saved to rbx is 4 or 5,
17
                                                 # which is the length of "true" or "false". 
18
   0x00401224 <+36>:    mov    %rax,%rsi         # Save the starting address of the string in rsi, which is the second parameter of memcpY.
19
   0x00401227 <+39>:    mov    %rbx,%rdx         # Save the length of the string in rdx, which is the third parameter of memcpy.
20
   0x0040122a <+42>:    callq  <memcpy@plt>      # Call memcpy.
21
   0x0040122f <+47>:    mov    %rbx,0x8(%r14)    # Save the length of the string in string::size.
22
   0x00401233 <+51>:    movb   $0x0,0x10(%r14,%rbx,1)  # Add '\0' to the end of the string.
23
   0x00401239 <+57>:    mov    %r14,%rax         # Save the String address in rax, that is, the return value.
24
   0x0040123c <+60>:    add    $0x8,%rsp
25
   0x00401240 <+64>:    pop    %rbx
26
   0x00401241 <+65>:    pop    %r14
27
   0x00401243 <+67>:    retq
28
End of assembler dump.



At this point, the situation becomes crystal clear:

  1. Clang++ assumes that the value of a Boolean is either 0 or 1.
  2. During the compiling, the compiler has the length of true and false.
  3. The compiler uses the XOR operations (0x5 ^ false == 5, 0x5 ^ true == 4) to calculate the length of the string to be copied.
  4. When the compiler finds that the bool type value does not conform to the preceding assumption, the length calculation goes wrong.
  5. Because the target address of memcpy is on the stack (for this example only), the stack buffer may overflow, causing the program to run off the rail and the backtrace information to be missing.

NOTE: [1]. The C++ standard requires a bool type value to represent at least two states: true and false, but does not specify the sizeof(bool). But on almost all compilers, a bool type value takes up an addressing unit, i.e., a byte. Therefore, from the storage perspective, the value range is from 0x00 to 0xFF, which represents 256 states.

Crash (computing) optimization Clang

Published at DZone with permission of Jamie Liu. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Scalable Framework for Enterprise Salesforce Optimization: Turning Outcomes Into an Operating System
  • Performance Optimization Techniques in Flutter 3.41 for Mobile App Development
  • Stop Burning Money on AI Inference: A Cloud-Agnostic Guide to Serverless Cost Optimization
  • Why Image Optimization in Modern Applications Matters More Than You Think

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook