In the following Java snippet, methods are defined to get and set a long field in an instance of a class that is shared across multiple threads. Because operations on double and long are nonatomic in Java, concurrent access may cause unexpected behavior. Thus, all operations on long and double fields should be synchronized.
BadJava
private long someLongValue;public long getLongValue() {return someLongValue;} public void setLongValue(long l) {someLongValue = l;}
This code tries to obtain a lock for a file, then writes to it.
PHP by default will wait indefinitely until a file lock is released. If an attacker is able to obtain the file lock, this code will pause execution, possibly leading to denial of service for other users. Note that in this case, if an attacker can perform an flock() on the file, they may already have privileges to destroy the log file. However, this still impacts the execution of other programs that depend on flock().
BadPHP
function writeToLog($message){$logfile = fopen("logFile.log", "a"); //attempt to get logfile lock if (flock($logfile, LOCK_EX)) {fwrite($logfile,$message); // unlock logfile flock($logfile, LOCK_UN);}else {print "Could not obtain lock on logFile.log, message not recorded\n";}}fclose($logFile);
The following function attempts to acquire a lock in order to perform operations on a shared resource.
However, the code does not check the value returned by pthread_mutex_lock() for errors. If pthread_mutex_lock() cannot acquire the mutex for any reason, the function may introduce a race condition into the program and result in undefined behavior.
BadC
void f(pthread_mutex_t *mutex) { pthread_mutex_lock(mutex); /* access shared resource */ pthread_mutex_unlock(mutex); }
The following function attempts to acquire a lock in order to perform operations on a shared resource.
However, the code does not check the value returned by pthread_mutex_lock() for errors. If pthread_mutex_lock() cannot acquire the mutex for any reason, the function may introduce a race condition into the program and result in undefined behavior.
GoodC
int f(pthread_mutex_t *mutex) { int result; result = pthread_mutex_lock(mutex);if (0 != result)return result; /* access shared resource */ return pthread_mutex_unlock(mutex); }
It may seem that the following bit of code achieves thread safety while avoiding unnecessary synchronization...
The programmer wants to guarantee that only one Helper() object is ever allocated, but does not want to pay the cost of synchronization every time this code is called.
BadJava
if (helper == null) { synchronized (this) {if (helper == null) {helper = new Helper();}} }return helper;
It may seem that the following bit of code achieves thread safety while avoiding unnecessary synchronization...
The programmer wants to guarantee that only one Helper() object is ever allocated, but does not want to pay the cost of synchronization every time this code is called.
BadJava
helper = new Helper();