Skip to content

Instantly share code, notes, and snippets.

@lingol
Created April 10, 2024 12:43
Show Gist options
  • Save lingol/622af352e090e0490ebacfe3a38b9221 to your computer and use it in GitHub Desktop.
Save lingol/622af352e090e0490ebacfe3a38b9221 to your computer and use it in GitHub Desktop.
#include <pthread.h>
#include <cstdint>
#include <cstring>
/// a POC of OHOS's libc pthread mutex memory corruption bug
/// this file is published in BSD 3-Clause License
static void pthreadMutexMemoryCorruptPOC() {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t stackMutex = {};
pthread_mutex_init(&stackMutex, &attr);
size_t size = sizeof(pthread_mutex_t);
pthread_mutex_t *heapMutex = (pthread_mutex_t *)malloc(size);
pthread_mutex_init(heapMutex, &attr);
pthread_mutexattr_destroy(&attr);
pthread_mutex_lock(&stackMutex);
pthread_mutex_lock(heapMutex);
pthread_mutex_lock(heapMutex);
pthread_mutex_unlock(heapMutex);
// one less unlock() will trigger this crash
// pthread_mutex_unlock(heapMutex);
pthread_mutex_destroy(heapMutex);
free(heapMutex);
pthread_mutex_unlock(&stackMutex);
size_t count = size / sizeof(char);
char *buffer = (char *)calloc(count, sizeof(char));
for (size_t index = 0; index < count; index++) {
if (buffer[index] != 0) {
abort();
}
}
pthread_mutex_lock(&stackMutex);
for (size_t index = 0; index < count; index++) {
if (buffer[index] != 0) {
// it will fail
abort();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment