From fdb893ede19df7649afd6c6c6ee7e6e666828d10 Mon Sep 17 00:00:00 2001
From: Mark Andrews <marka@isc.org>
Date: Thu, 15 Oct 2020 16:48:24 +1100
Subject: [PATCH] Address data race in dns_stats_detach over references

    WARNING: ThreadSanitizer: data race
    Write of size 4 at 0x000000000001 by thread T1 (mutexes: write M1):
    #0 dns_stats_detach lib/dns/stats.c:115:19
    #1 destroy lib/dns/view.c:527:3
    #2 dns_view_weakdetach lib/dns/view.c:704:3
    #3 zone_free lib/dns/zone.c:1149:3
    #4 zone_shutdown lib/dns/zone.c:13123:3
    #5 dispatch lib/isc/task.c:1157:7
    #6 run lib/isc/task.c:1331:2

    Previous read of size 4 at 0x000000000001 by thread T2:
    #0 dns_stats_detach lib/dns/stats.c:118:13
    #1 destroy lib/dns/view.c:527:3
    #2 dns_view_weakdetach lib/dns/view.c:704:3
    #3 zone_free lib/dns/zone.c:1152:3
    #4 zone_shutdown lib/dns/zone.c:13123:3
    #5 dispatch lib/isc/task.c:1157:7
    #6 run lib/isc/task.c:1331:2
Conflict: NA
Reference: https://gitlab.isc.org/isc-projects/bind9/-/commit/fdb893ede19df7649afd6c6c6ee7e6e666828d10
---
 lib/dns/stats.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/lib/dns/stats.c b/lib/dns/stats.c
index 1473371c64..a0184ecf84 100644
--- a/lib/dns/stats.c
+++ b/lib/dns/stats.c
@@ -104,6 +104,7 @@ dns_stats_attach(dns_stats_t *stats, dns_stats_t **statsp) {
 
 void
 dns_stats_detach(dns_stats_t **statsp) {
+	unsigned int references;
 	dns_stats_t *stats;
 
 	REQUIRE(statsp != NULL && DNS_STATS_VALID(*statsp));
@@ -112,10 +113,10 @@ dns_stats_detach(dns_stats_t **statsp) {
 	*statsp = NULL;
 
 	LOCK(&stats->lock);
-	stats->references--;
+	references = --stats->references;
 	UNLOCK(&stats->lock);
 
-	if (stats->references == 0) {
+	if (references == 0) {
 		isc_stats_detach(&stats->counters);
 		DESTROYLOCK(&stats->lock);
 		isc_mem_putanddetach(&stats->mctx, stats, sizeof(*stats));
-- 
2.23.0

