From daaa9bf1df866c03a3c5a58fe202cf98923437ac Mon Sep 17 00:00:00 2001
From: Marcelo Araujo <araujo@FreeBSD.org>
Date: Fri, 16 Jun 2017 01:26:01 +0000
Subject: [PATCH] Check if pthread_create(3) successfully created the thread
 prior to call pthread_join(3). The variable tid is not yet initialized in
 case the authentication fails at early stage, that would lead pthread_join be
 called with an uninitialized variable.

CID:		1375950
Reported by:	Coverity, cem
Reviewed by:	cem
MFC after:	3 weeks.
Sponsored by:	iXsystems, Inc.
Differential Revision:	https://reviews.freebsd.org/D11150
---
 usr.sbin/bhyve/rfb.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/usr.sbin/bhyve/rfb.c b/usr.sbin/bhyve/rfb.c
index 0b312641b2fc..0f492e1b9d48 100644
--- a/usr.sbin/bhyve/rfb.c
+++ b/usr.sbin/bhyve/rfb.c
@@ -769,6 +769,7 @@ rfb_handle(struct rfb_softc *rc, int cfd)
 	pthread_t tid;
 	uint32_t sres = 0;
 	int len;
+	int perror = 1;
 
 	rc->cfd = cfd;
 
@@ -878,8 +879,9 @@ rfb_handle(struct rfb_softc *rc, int cfd)
 
 	rfb_send_screen(rc, cfd, 1);
 
-	pthread_create(&tid, NULL, rfb_wr_thr, rc);
-	pthread_set_name_np(tid, "rfbout");
+	perror = pthread_create(&tid, NULL, rfb_wr_thr, rc);
+	if (perror == 0)
+		pthread_set_name_np(tid, "rfbout");
 
         /* Now read in client requests. 1st byte identifies type */
 	for (;;) {
@@ -915,7 +917,8 @@ rfb_handle(struct rfb_softc *rc, int cfd)
 	}
 done:
 	rc->cfd = -1;
-	pthread_join(tid, NULL);
+	if (perror == 0)
+		pthread_join(tid, NULL);
 	if (rc->enc_zlib_ok)
 		deflateEnd(&rc->zstream);
 }