pthread_key_create() should avoid key#0

Poul-Henning Kamp phk at freebsd.org
Tue May 14 09:52:16 UTC 2013


I think this patch would be a good idea, it avoids allocing
a thread specific key with numeric value zero, which helps
expose cases where a key hasn't been allocated in the first
place.


Index: libkse/thread/thr_spec.c
===================================================================
--- libkse/thread/thr_spec.c	(revision 248293)
+++ libkse/thread/thr_spec.c	(working copy)
@@ -59,7 +59,7 @@
 
 	/* Lock the key table: */
 	THR_LOCK_ACQUIRE(curthread, &_keytable_lock);
-	for (i = 0; i < PTHREAD_KEYS_MAX; i++) {
+	for (i = 1; i < PTHREAD_KEYS_MAX; i++) {
 
 		if (_thread_keytable[i].allocated == 0) {
 			_thread_keytable[i].allocated = 1;
@@ -84,7 +84,7 @@
 	struct pthread *curthread = _get_curthread();
 	int ret = 0;
 
-	if ((unsigned int)key < PTHREAD_KEYS_MAX) {
+	if (key > 0 && (unsigned int)key < PTHREAD_KEYS_MAX) {
 		/* Lock the key table: */
 		THR_LOCK_ACQUIRE(curthread, &_keytable_lock);
 
Index: libthr/thread/thr_spec.c
===================================================================
--- libthr/thread/thr_spec.c	(revision 248293)
+++ libthr/thread/thr_spec.c	(working copy)
@@ -61,7 +61,7 @@
 
 	/* Lock the key table: */
 	THR_LOCK_ACQUIRE(curthread, &_keytable_lock);
-	for (i = 0; i < PTHREAD_KEYS_MAX; i++) {
+	for (i = 1; i < PTHREAD_KEYS_MAX; i++) {
 
 		if (_thread_keytable[i].allocated == 0) {
 			_thread_keytable[i].allocated = 1;
@@ -86,7 +86,7 @@
 	struct pthread *curthread = _get_curthread();
 	int ret = 0;
 
-	if ((unsigned int)key < PTHREAD_KEYS_MAX) {
+	if (key > 0 && (unsigned int)key < PTHREAD_KEYS_MAX) {
 		/* Lock the key table: */
 		THR_LOCK_ACQUIRE(curthread, &_keytable_lock);
 

-- 
Poul-Henning Kamp       | UNIX since Zilog Zeus 3.20
phk at FreeBSD.ORG         | TCP/IP since RFC 956
FreeBSD committer       | BSD since 4.3-tahoe
Never attribute to malice what can adequately be explained by incompetence.


More information about the freebsd-threads mailing list