目录

Optimization Suggestions for CppCrash Issues

Optimization Suggestion 1: Avoid Data Races When Using the STL Library such as map, vector, list, and set.

Incorrect example:

void EraseMapItem1(int key)
{
    appRunningRecordMap_.erase(key);
}

When one thread is deleting elements of a map container, another thread operates on the same map at the same time, it will cause crash.

Correct example:

void EraseMapItem2(int key)
{
    // Lock.
    std::lock_guard<std::mutex> lock(mutex_);
    appRunningRecordMap_.erase(key);
}

void FindMapItem(int key)
{
    // Lock.
    std::lock_guard<std::mutex> lock(mutex_);
    appRunningRecordMap_.find(key);
}

Optimization Suggestion 2: If Multiple Threads Access Global Variables, Static Variables, or Class Member Variables and Perform Modification or Deletion, All Operations Must Be Locked for Protection.

Incorrect example:

std::list<std::shared_ptr<Object>> g_list;

void MainFunc()
{
    auto xxx = std::make_shared<Object>();
    g_list.push_back(xxx);
}

// Thread 1
void Thread1Func()
{
    for (auto &ptr : g_list) {
        ptr->method();
    }
}

// Thread 2
void Thread2Func()
{
    g_list.clear(); // Clearing the list may cause thread 1 to crash when using g_list.
}

Correct example:

// Thread 1
void Thread1FuncEx()
{
    std::lock_guard<std::mutex> lock(mutexEx_);
    for (auto &ptr : g_list) {
        ptr->method();
    }
}

// Thread 2
void Thread2FuncEx()
{
    std::lock_guard<std::mutex> lock(mutexEx_);
    g_list.clear();
}

Optimization Suggestion 3: Use Reference Captures in Lambda Expressions in Asynchronous Scenarios with Caution, and Pay Attention to Object Lifetime.

Incorrect example:

void Checker::Detection(std::string& url)
{
    handler.PostAsyncTask(
        [this, &url]() {
            if (!Checker::DoCheck(url)) {
                // ...
            }
        }
    );
    // The url variable is about to be destructed.
}

bool Checker::DoCheck(const std::string& url)
{
    // ...
    return true;
}

Correct example:

void Checker::Detection2(std::string& url)
{
    handler.PostAsyncTask(
        [this, url]() {
            if (!Checker::DoCheck(url)) {
                // ...
            }
        }
    );
    // The url variable is about to be destructed, but the lambda already has its own copy.
}

Optimization Suggestion 4: Check Whether the Smart Pointer and Raw Pointer Are Null Before Using Them.

Incorrect example:

std::shared_ptr<Object> smartPointer = nullptr;
smartPointer->method();

Correct example:

std::shared_ptr<Object> smartPointer = nullptr;
if (smartPointer != nullptr) {
    smartPointer->method();
}

Optimization Suggestion 5: Do Not Use Multiple Smart Pointers to Manage the Same Raw Pointer.

Incorrect example:

Object* xxx = new Object();
std::shared_ptr<Object> xxx1(xxx); // When the reference count of xxx1 is reduced to 0, xxx is destructed once.
std::shared_ptr<Object> xxx2(xxx); // When the reference count of xxx2 is reduced to 0, xxx is destructed once.

Correct example:

std::shared_ptr<Object> xxx = std::make_shared<Object>();

Optimization Suggestion 6: Do Not Extract Raw Pointers from Smart Pointers for Further Use.

Incorrect example:

auto smartPointer = std::make_shared<Object>(); // smartPointer is destructed when its reference count is reduced to 0.
auto pointer = smartPointer.get();
pointer->method(); // A crash may occur if pointer is used after smartPinter is destructed.

Correct example:

auto smartPointer = std::make_shared<Object>();
smartPointer->method();

Optimization Suggestion 7: Do Not Continue to Use or Proactively Release a Raw Pointer After It Is Constructed as a Smart Pointer.

Incorrect example:

Object* pointer = new Object();
std::shared_ptr<Object> smartPointer(pointer); // smartPointer is destructed when its reference count is reduced to 0.
pointer->method(); // A crash may occur if pointer is used after smartPointer is destructed.
delete pointer; // A crash occurs when the raw pointer is proactively released.

Correct example:

auto smartPointer = std::make_shared<Object>();
smartPointer->method();

Optimization Suggestion 8: Do Not Call Non-asynchronous-safe Functions or Use STL Libraries such as map, vector, list, and set During Signal Handling.

Incorrect example:

static void SignalHandler(int signo, siginfo_t* si, void* context) // Signal handling function
{
    char *c = (char*)malloc(10); // Do not use malloc, which is a non-asynchronous-safe function.
}

Correct example:

static void SignalHandlerEx(int signo, siginfo_t* si, void* context) // Signal handling function
{
    char c[10] = {0};
}

Ensure that the objects or functions directly or indirectly called by the signal handling function are asynchronous safe.

malloc is a non-asynchronous-safe function. Therefore, in the signal handling function:

  1. Do not allocate memory on the heap.
  2. Do not use STL objects, such as string, vector, list, set, and map, that dynamically allocate memory on the heap.
  3. Ensure that the called external function is asynchronous-safe. Typical non-asynchronous security functions include getproctid, fgets, and fopen.

Asynchronous-safe functions

If a function can be securely called and also securely used in a signal handler, the function is asynchronous-safe or asynchronous-signal-safe. The following table lists asynchronous-safe functions, referenced from POSIX standards. Apps can call asynchronous-safe functions in signal handlers.

_Exit()

fexecve()

posix_trace_event()

sigprocmask()

_exit()

fork()

pselect()

sigqueue()

abort()

fstat()

pthread_kill()

sigset()

accept()

fstatat()

pthread_self()

sigsuspend()

access()

fsync()

pthread_sigmask()

sleep()

aio_error()

ftruncate()

raise()

sockatmark()

aio_return()

futimens()

read()

socket()

aio_suspend()

getegid()

readlink()

socketpair()

alarm()

geteuid()

readlinkat()

stat()

bind()

getgid()

recv()

symlink()

cfgetispeed()

getgroups()

recvfrom()

symlinkat()

cfgetospeed()

getpeername()

recvmsg()

tcdrain()

cfsetispeed()

getpgrp()

rename()

tcflow()

cfsetospeed()

getpid()

renameat()

tcflush()

chdir()

getppid()

rmdir()

tcgetattr()

chmod()

getsockname()

select()

tcgetpgrp()

chown()

getsockopt()

sem_post()

tcsendbreak()

clock_gettime()

getuid()

send()

tcsetattr()

close()

kill()

sendmsg()

tcsetpgrp()

connect()

link()

sendto()

time()

creat()

linkat()

setgid()

timer_getoverrun()

dup()

listen()

setpgid()

timer_gettime()

dup2()

lseek()

setsid()

timer_settime()

execl()

lstat()

setsockopt()

times()

execle()

mkdir()

setuid()

umask()

execv()

mkdirat()

shutdown()

uname()

execve()

mkfifo()

sigaction()

unlink()

faccessat()

mkfifoat()

sigaddset()

unlinkat()

fchdir()

mknod()

sigdelset()

utime()

fchmod()

mknodat()

sigemptyset()

utimensat()

fchmodat()

open()

sigfillset()

utimes()

fchown()

openat()

sigismember()

wait()

fchownat()

pause()

signal()

waitpid()

fcntl()

pipe()

sigpause()

write()

fdatasync()

poll()

sigpending()

  

Optimization Suggestion 9: Do Not Pass the this Pointer to Other Modules or Threads.

It is dangerous to pass the this pointer to other modules or threads. If the lifetime of other modules or threads is inconsistent with that of the object to which the this pointer points, a crash may occur.

Incorrect example:

void Object1::Run()
{
    startThread_ = std::shared_ptr<std::thread>(new std::thread([this] { // Pass the this pointer to another thread.
        if (this == nullptr) {
            return;
        }
        this->GetInfo();
        // ...
    }));
    // ...
}

Correct example:

class Object2 : public std::enable_shared_from_this<Object2> {
public:
    void Run();
    void GetInfo() {}
    // ...

private:
    std::shared_ptr<std::thread> startThread_;
    // ...
};

void Object2::Run()
{
    std::weak_ptr<Object2> weakPtr = shared_from_this(); // Call shared_from_this to capture this. (weak_from_this can be used since C++17.)
    startThread_ = std::shared_ptr<std::thread>(new std::thread([weakPtr] { // Pass weakPtr to another thread.
        auto ptr = weakPtr.lock();
        if (ptr == nullptr) {
            return;
        }
        ptr->GetInfo();
        // ...
    }));
    // ...
}

void MainFuncEx()
{
    auto object = std::make_shared<Object2>(); // The smart pointer must be used to initialize the object.
    object->Run();
}

Optimization Suggestion 10: Do Not Return References to Local Variables from APIs.

Incorrect example:

std::string& GetString()
{
    std::string result = "this is string";
    return result; // Do not return the reference to the local variable result.
}

Correct example:

std::string GetStringEx()
{
    std::string result = "this is string";
    return result; // Return the value of the local variable.
}