patch 9.1.1339: missing out-of-memory checks for enc_to_utf16()/utf16_to_enc()

Problem:  missing out-of-memory checks for enc_to_utf16() and
          utf16_to_enc()
Solution: Add out-of-memory checks and fix a few other minor issues
          (John Marriott)

This change does:
-  add missing out-of-memory checks for enc_to_utf16() and
   utf16_to_enc()
-  add a small optimisation in mch_errmsg_c() and mch_msg_c() (in
   message.c) to only call STRLEN() if needed.
-  fix a memory leak in winpty_term_and_job_init() (in terminal.c).

closes: #17191

Signed-off-by: John Marriott <basilisk@internode.on.net>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/terminal.c b/src/terminal.c
index 88791b8..29926bf 100644
--- a/src/terminal.c
+++ b/src/terminal.c
@@ -7083,7 +7083,11 @@
     if (cmd_wchar == NULL)
 	goto failed;
     if (opt->jo_cwd != NULL)
+    {
 	cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
+	if (cwd_wchar == NULL)
+	    goto failed;
+    }
 
     win32_build_env(opt->jo_env, &ga_env, TRUE);
     env_wchar = ga_env.ga_data;
@@ -7425,7 +7429,11 @@
     if (cmd_wchar == NULL)
 	goto failed;
     if (opt->jo_cwd != NULL)
+    {
 	cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
+	if (cwd_wchar == NULL)
+	    goto failed;
+    }
 
     win32_build_env(opt->jo_env, &ga_env, TRUE);
     env_wchar = ga_env.ga_data;
@@ -7585,7 +7593,11 @@
 	char *msg = (char *)utf16_to_enc(
 				(short_u *)winpty_error_msg(winpty_err), NULL);
 
-	emsg(msg);
+	if (msg != NULL)
+	{
+	    emsg(msg);
+	    vim_free(msg);
+	}
 	winpty_error_free(winpty_err);
     }
     return FAIL;