git: 1a233fd31769 - stable/13 - sort: Fix message catalogue usage

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Fri, 04 Feb 2022 14:58:23 UTC
The branch stable/13 has been updated by markj:

URL: https://cgit.FreeBSD.org/src/commit/?id=1a233fd317690e5eaed1476756ac3e991ca03ff2

commit 1a233fd317690e5eaed1476756ac3e991ca03ff2
Author:     Mark Johnston <markj@FreeBSD.org>
AuthorDate: 2022-01-28 17:49:28 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2022-02-04 14:58:13 +0000

    sort: Fix message catalogue usage
    
    - Check that catopen() succeeded before calling catclose().  musl will
      crash in the latter if the catalogue descriptor is -1.
    - Keep the message catalogue open for most of sort(1)'s actual
      operation.
    - Don't use catgets(3) to print error messages if catopen(3) had failed.
    
    Reviewed by:    arichardson, emaste
    Sponsored by:   The FreeBSD Foundation
    
    (cherry picked from commit 8d8b9b560afdf88f5537f259a4a14660d2a85b1f)
---
 usr.bin/sort/sort.c | 19 ++++++++++---------
 usr.bin/sort/sort.h |  3 ++-
 2 files changed, 12 insertions(+), 10 deletions(-)

diff --git a/usr.bin/sort/sort.c b/usr.bin/sort/sort.c
index 0fbbd9284aad..b7c8107cc22d 100644
--- a/usr.bin/sort/sort.c
+++ b/usr.bin/sort/sort.c
@@ -57,7 +57,7 @@ __FBSDID("$FreeBSD$");
 
 #ifndef WITHOUT_NLS
 #include <nl_types.h>
-nl_catd catalog;
+nl_catd catalog = (nl_catd)-1;
 #endif
 
 #define	OPTIONS	"bcCdfghik:Mmno:RrsS:t:T:uVz"
@@ -1011,6 +1011,10 @@ main(int argc, char **argv)
 	set_tmpdir();
 	set_sort_opts();
 
+#ifndef WITHOUT_NLS
+	catalog = catopen("sort", NL_CAT_LOCALE);
+#endif
+
 	fix_obsolete_keys(&argc, argv);
 
 	while (((c = getopt_long(argc, argv, OPTIONS, long_options, NULL))
@@ -1194,17 +1198,9 @@ main(int argc, char **argv)
 		argv = argv_from_file0;
 	}
 
-#ifndef WITHOUT_NLS
-	catalog = catopen("sort", NL_CAT_LOCALE);
-#endif
-
 	if (sort_opts_vals.cflag && sort_opts_vals.mflag)
 		errx(1, "%c:%c: %s", 'm', 'c', getstr(1));
 
-#ifndef WITHOUT_NLS
-	catclose(catalog);
-#endif
-
 	if (keys_num == 0) {
 		keys_num = 1;
 		keys = sort_realloc(keys, sizeof(struct key_specs));
@@ -1343,5 +1339,10 @@ main(int argc, char **argv)
 
 	sort_free(outfile);
 
+#ifndef WITHOUT_NLS
+	if (catalog != (nl_catd)-1)
+		catclose(catalog);
+#endif
+
 	return (result);
 }
diff --git a/usr.bin/sort/sort.h b/usr.bin/sort/sort.h
index 96b36a65f4e4..47ce6ea29ab3 100644
--- a/usr.bin/sort/sort.h
+++ b/usr.bin/sort/sort.h
@@ -49,7 +49,8 @@
 #include <nl_types.h>
 
 extern nl_catd catalog;
-#define	getstr(n)	 catgets(catalog, 1, n, nlsstr[n])
+#define	getstr(n)	\
+	(catalog == (nl_catd)-1 ? nlsstr[n] : catgets(catalog, 1, n, nlsstr[n]))
 #endif
 
 extern const char *nlsstr[];