xref: /titanic_50/usr/src/cmd/ptools/pargs/pargs.c (revision 25cf1a301a396c38e8adf52c15f537b80d2483f7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * pargs examines and prints the arguments (argv), environment (environ),
31  * and auxiliary vector of another process.
32  *
33  * This utility is made more complex because it must run in internationalized
34  * environments.  The two key cases for pargs to manage are:
35  *
36  * 1. pargs and target run in the same locale: pargs must respect the
37  * locale, but this case is straightforward.  Care is taken to correctly
38  * use wide characters in order to print results properly.
39  *
40  * 2. pargs and target run in different locales: in this case, pargs examines
41  * the string having assumed the victim's locale.  Unprintable (but valid)
42  * characters are escaped.  Next, iconv(3c) is used to convert between the
43  * target and pargs codeset.  Finally, a second pass to escape unprintable
44  * (but valid) characters is made.
45  *
46  * In any case in which characters are encountered which are not valid in
47  * their purported locale, the string "fails" and is treated as a traditional
48  * 7-bit ASCII encoded string, and escaped accordingly.
49  */
50 
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <locale.h>
54 #include <wchar.h>
55 #include <iconv.h>
56 #include <langinfo.h>
57 #include <unistd.h>
58 #include <ctype.h>
59 #include <fcntl.h>
60 #include <string.h>
61 #include <strings.h>
62 #include <limits.h>
63 #include <pwd.h>
64 #include <grp.h>
65 #include <errno.h>
66 #include <setjmp.h>
67 #include <sys/types.h>
68 #include <sys/auxv.h>
69 #include <sys/archsystm.h>
70 #include <sys/proc.h>
71 #include <sys/elf.h>
72 #include <libproc.h>
73 #include <wctype.h>
74 #include <widec.h>
75 #include <elfcap.h>
76 
77 typedef struct pargs_data {
78 	struct ps_prochandle *pd_proc;	/* target proc handle */
79 	psinfo_t *pd_psinfo;		/* target psinfo */
80 	char *pd_locale;		/* target process locale */
81 	int pd_conv_flags;		/* flags governing string conversion */
82 	iconv_t pd_iconv;		/* iconv conversion descriptor */
83 	size_t pd_argc;
84 	uintptr_t *pd_argv;
85 	char **pd_argv_strs;
86 	size_t pd_envc;
87 	uintptr_t *pd_envp;
88 	char **pd_envp_strs;
89 	size_t pd_auxc;
90 	auxv_t *pd_auxv;
91 	char **pd_auxv_strs;
92 	char *pd_execname;
93 } pargs_data_t;
94 
95 #define	CONV_USE_ICONV		0x01
96 #define	CONV_STRICT_ASCII	0x02
97 
98 static char *command;
99 static int dmodel;
100 
101 #define	EXTRACT_BUFSZ 128		/* extract_string() initial size */
102 #define	ENV_CHUNK 16			/* #env ptrs to read at a time */
103 
104 static jmp_buf env;			/* malloc failure handling */
105 
106 static void *
107 safe_zalloc(size_t size)
108 {
109 	void *p;
110 
111 	/*
112 	 * If the malloc fails we longjmp out to allow the code to Prelease()
113 	 * a stopped victim if needed.
114 	 */
115 	if ((p = malloc(size)) == NULL) {
116 		longjmp(env, errno);
117 	}
118 
119 	bzero(p, size);
120 	return (p);
121 }
122 
123 static char *
124 safe_strdup(const char *s1)
125 {
126 	char	*s2;
127 
128 	s2 = safe_zalloc(strlen(s1) + 1);
129 	(void) strcpy(s2, s1);
130 	return (s2);
131 }
132 
133 /*
134  * Given a wchar_t which might represent an 'escapable' sequence (see
135  * formats(5)), return the base ascii character needed to print that
136  * sequence.
137  *
138  * The comparisons performed may look suspect at first, but all are valid;
139  * the characters below all appear in the "Portable Character Set."  The
140  * Single Unix Spec says: "The wide-character value for each member of the
141  * Portable Character Set will equal its value when used as the lone
142  * character in an integer character constant."
143  */
144 static uchar_t
145 get_interp_char(wchar_t wc)
146 {
147 	switch (wc) {
148 	case L'\a':
149 		return ('a');
150 	case L'\b':
151 		return ('b');
152 	case L'\f':
153 		return ('f');
154 	case L'\n':
155 		return ('n');
156 	case L'\r':
157 		return ('r');
158 	case L'\t':
159 		return ('t');
160 	case L'\v':
161 		return ('v');
162 	case L'\\':
163 		return ('\\');
164 	}
165 	return ('\0');
166 }
167 
168 static char *
169 unctrl_str_strict_ascii(const char *src, int escape_slash, int *unprintable)
170 {
171 	uchar_t *uc, *ucp, c, ic;
172 	uc = ucp = safe_zalloc((strlen(src) * 4) + 1);
173 	while ((c = *src++) != '\0') {
174 		/*
175 		 * Call get_interp_char *first*, since \ will otherwise not
176 		 * be escaped as \\.
177 		 */
178 		if ((ic = get_interp_char((wchar_t)c)) != '\0') {
179 			if (escape_slash || ic != '\\')
180 				*ucp++ = '\\';
181 			*ucp++ = ic;
182 		} else if (isascii(c) && isprint(c)) {
183 			*ucp++ = c;
184 		} else {
185 			*ucp++ = '\\';
186 			*ucp++ = ((c >> 6) & 7) + '0';
187 			*ucp++ = ((c >> 3) & 7) + '0';
188 			*ucp++ = (c & 7) + '0';
189 			*unprintable = 1;
190 		}
191 	}
192 	*ucp = '\0';
193 	return ((char *)uc);
194 }
195 
196 /*
197  * Convert control characters as described in format(5) to their readable
198  * representation; special care is taken to handle multibyte character sets.
199  *
200  * If escape_slash is true, escaping of '\' occurs.  The first time a string
201  * is unctrl'd, this should be '1'.  Subsequent iterations over the same
202  * string should set escape_slash to 0.  Otherwise you'll wind up with
203  * \ --> \\ --> \\\\.
204  */
205 static char *
206 unctrl_str(const char *src, int escape_slash, int *unprintable)
207 {
208 	wchar_t wc;
209 	wchar_t *wide_src, *wide_srcp;
210 	wchar_t *wide_dest, *wide_destp;
211 	char *uc;
212 	size_t srcbufsz = strlen(src) + 1;
213 	size_t destbufsz = srcbufsz * 4;
214 	size_t srclen, destlen;
215 
216 	wide_srcp = wide_src = safe_zalloc(srcbufsz * sizeof (wchar_t));
217 	wide_destp = wide_dest = safe_zalloc(destbufsz * sizeof (wchar_t));
218 
219 	if ((srclen = mbstowcs(wide_src, src, srcbufsz - 1)) == (size_t)-1) {
220 		/*
221 		 * We can't trust the string, since in the locale in which
222 		 * this call is operating, the string contains an invalid
223 		 * multibyte sequence.  There isn't much to do here, so
224 		 * convert the string byte by byte to wide characters, as
225 		 * if it came from a C locale (char) string.  This isn't
226 		 * perfect, but at least the characters will make it to
227 		 * the screen.
228 		 */
229 		free(wide_src);
230 		free(wide_dest);
231 		return (unctrl_str_strict_ascii(src, escape_slash,
232 		    unprintable));
233 	}
234 	if (srclen == (srcbufsz - 1)) {
235 		wide_src[srclen] = L'\0';
236 	}
237 
238 	while ((wc = *wide_srcp++) != L'\0') {
239 		char cvt_buf[MB_LEN_MAX];
240 		int len, i;
241 		char c = get_interp_char(wc);
242 
243 		if ((c != '\0') && (escape_slash || c != '\\')) {
244 			/*
245 			 * Print "interpreted version" (\n, \a, etc).
246 			 */
247 			*wide_destp++ = L'\\';
248 			*wide_destp++ = (wchar_t)c;
249 			continue;
250 		}
251 
252 		if (iswprint(wc)) {
253 			*wide_destp++ = wc;
254 			continue;
255 		}
256 
257 		/*
258 		 * Convert the wide char back into (potentially several)
259 		 * multibyte characters, then escape out each of those bytes.
260 		 */
261 		bzero(cvt_buf, sizeof (cvt_buf));
262 		if ((len = wctomb(cvt_buf, wc)) == -1) {
263 			/*
264 			 * This is a totally invalid wide char; discard it.
265 			 */
266 			continue;
267 		}
268 		for (i = 0; i < len; i++) {
269 			uchar_t c = cvt_buf[i];
270 			*wide_destp++ = L'\\';
271 			*wide_destp++ = (wchar_t)('0' + ((c >> 6) & 7));
272 			*wide_destp++ = (wchar_t)('0' + ((c >> 3) & 7));
273 			*wide_destp++ = (wchar_t)('0' + (c & 7));
274 			*unprintable = 1;
275 		}
276 	}
277 
278 	*wide_destp = '\0';
279 	destlen = (wide_destp - wide_dest) * MB_CUR_MAX + 1;
280 	uc = safe_zalloc(destlen);
281 	if (wcstombs(uc, wide_dest, destlen) == (size_t)-1) {
282 		/* If we've gotten this far, wcstombs shouldn't fail... */
283 		(void) fprintf(stderr, "%s: wcstombs failed unexpectedly: %s\n",
284 		    command, strerror(errno));
285 		exit(1);
286 	} else {
287 		char *tmp;
288 		/*
289 		 * Try to save memory; don't waste 3 * strlen in the
290 		 * common case.
291 		 */
292 		tmp = safe_strdup(uc);
293 		free(uc);
294 		uc = tmp;
295 	}
296 	free(wide_dest);
297 	free(wide_src);
298 	return (uc);
299 }
300 
301 /*
302  * These functions determine which characters are safe to be left unquoted.
303  * Rather than starting with every printable character and subtracting out the
304  * shell metacharacters, we take the more conservative approach of starting with
305  * a set of safe characters and adding those few common punctuation characters
306  * which are known to be safe.  The rules are:
307  *
308  * 	If this is a printable character (graph), and not punctuation, it is
309  * 	safe to leave unquoted.
310  *
311  * 	If it's one of known hard-coded safe characters, it's also safe to leave
312  * 	unquoted.
313  *
314  * 	Otherwise, the entire argument must be quoted.
315  *
316  * This will cause some strings to be unecessarily quoted, but it is safer than
317  * having a character unintentionally interpreted by the shell.
318  */
319 static int
320 issafe_ascii(char c)
321 {
322 	return (isalnum(c) || strchr("_.-/@:,", c) != NULL);
323 }
324 
325 static int
326 issafe(wchar_t wc)
327 {
328 	return ((iswgraph(wc) && !iswpunct(wc)) ||
329 	    wschr(L"_.-/@:,", wc) != NULL);
330 }
331 
332 /*ARGSUSED*/
333 static char *
334 quote_string_ascii(pargs_data_t *datap, char *src)
335 {
336 	char *dst;
337 	int quote_count = 0;
338 	int need_quote = 0;
339 	char *srcp, *dstp;
340 	size_t dstlen;
341 
342 	for (srcp = src; *srcp != '\0'; srcp++) {
343 		if (!issafe_ascii(*srcp)) {
344 			need_quote = 1;
345 			if (*srcp == '\'')
346 				quote_count++;
347 		}
348 	}
349 
350 	if (!need_quote)
351 		return (src);
352 
353 	/*
354 	 * The only character we care about here is a single quote.  All the
355 	 * other unprintable characters (and backslashes) will have been dealt
356 	 * with by unctrl_str().  We make the following subtitution when we
357 	 * encounter a single quote:
358 	 *
359 	 * 	' = '"'"'
360 	 *
361 	 * In addition, we put single quotes around the entire argument.  For
362 	 * example:
363 	 *
364 	 * 	foo'bar = 'foo'"'"'bar'
365 	 */
366 	dstlen = strlen(src) + 3 + 4 * quote_count;
367 	dst = safe_zalloc(dstlen);
368 
369 	dstp = dst;
370 	*dstp++ = '\'';
371 	for (srcp = src; *srcp != '\0'; srcp++, dstp++) {
372 		*dstp = *srcp;
373 
374 		if (*srcp == '\'') {
375 			dstp[1] = '"';
376 			dstp[2] = '\'';
377 			dstp[3] = '"';
378 			dstp[4] = '\'';
379 			dstp += 4;
380 		}
381 	}
382 	*dstp++ = '\'';
383 	*dstp = '\0';
384 
385 	free(src);
386 
387 	return (dst);
388 }
389 
390 static char *
391 quote_string(pargs_data_t *datap, char *src)
392 {
393 	wchar_t *wide_src, *wide_srcp;
394 	wchar_t *wide_dest, *wide_destp;
395 	char *uc;
396 	size_t srcbufsz = strlen(src) + 1;
397 	size_t srclen;
398 	size_t destbufsz;
399 	size_t destlen;
400 	int quote_count = 0;
401 	int need_quote = 0;
402 
403 	if (datap->pd_conv_flags & CONV_STRICT_ASCII)
404 		return (quote_string_ascii(datap, src));
405 
406 	wide_srcp = wide_src = safe_zalloc(srcbufsz * sizeof (wchar_t));
407 
408 	if ((srclen = mbstowcs(wide_src, src, srcbufsz - 1)) == (size_t)-1) {
409 		free(wide_src);
410 		return (quote_string_ascii(datap, src));
411 	}
412 
413 	if (srclen == srcbufsz - 1)
414 		wide_src[srclen] = L'\0';
415 
416 	for (wide_srcp = wide_src; *wide_srcp != '\0'; wide_srcp++) {
417 		if (!issafe(*wide_srcp)) {
418 			need_quote = 1;
419 			if (*wide_srcp == L'\'')
420 				quote_count++;
421 		}
422 	}
423 
424 	if (!need_quote) {
425 		free(wide_src);
426 		return (src);
427 	}
428 
429 	/*
430 	 * See comment for quote_string_ascii(), above.
431 	 */
432 	destbufsz = srcbufsz + 3 + 4 * quote_count;
433 	wide_destp = wide_dest = safe_zalloc(destbufsz * sizeof (wchar_t));
434 
435 	*wide_destp++ = L'\'';
436 	for (wide_srcp = wide_src; *wide_srcp != L'\0';
437 	    wide_srcp++, wide_destp++) {
438 		*wide_destp = *wide_srcp;
439 
440 		if (*wide_srcp == L'\'') {
441 			wide_destp[1] = L'"';
442 			wide_destp[2] = L'\'';
443 			wide_destp[3] = L'"';
444 			wide_destp[4] = L'\'';
445 			wide_destp += 4;
446 		}
447 	}
448 	*wide_destp++ = L'\'';
449 	*wide_destp = L'\0';
450 
451 	destlen = destbufsz * MB_CUR_MAX + 1;
452 	uc = safe_zalloc(destlen);
453 	if (wcstombs(uc, wide_dest, destlen) == (size_t)-1) {
454 		/* If we've gotten this far, wcstombs shouldn't fail... */
455 		(void) fprintf(stderr, "%s: wcstombs failed unexpectedly: %s\n",
456 		    command, strerror(errno));
457 		exit(1);
458 	}
459 
460 	free(wide_dest);
461 	free(wide_src);
462 
463 	return (uc);
464 }
465 
466 
467 /*
468  * Determine the locale of the target process by traversing its environment,
469  * making only one pass for efficiency's sake; stash the result in
470  * datap->pd_locale.
471  *
472  * It's possible that the process has called setlocale() to change its
473  * locale to something different, but we mostly care about making a good
474  * guess as to the locale at exec(2) time.
475  */
476 static void
477 lookup_locale(pargs_data_t *datap)
478 {
479 	int i, j, composite = 0;
480 	size_t	len = 0;
481 	char	*pd_locale;
482 	char	*lc_all = NULL, *lang = NULL;
483 	char	*lcs[] = { NULL, NULL, NULL, NULL, NULL, NULL };
484 	static const char *cat_names[] = {
485 		"LC_CTYPE=",	"LC_NUMERIC=",	"LC_TIME=",
486 		"LC_COLLATE=",	"LC_MONETARY=",	"LC_MESSAGES="
487 	};
488 
489 	for (i = 0; i < datap->pd_envc; i++) {
490 		char *s = datap->pd_envp_strs[i];
491 
492 		if (s == NULL)
493 			continue;
494 
495 		if (strncmp("LC_ALL=", s, strlen("LC_ALL=")) == 0) {
496 			/*
497 			 * Minor optimization-- if we find LC_ALL we're done.
498 			 */
499 			lc_all = s + strlen("LC_ALL=");
500 			break;
501 		}
502 		for (j = 0; j <= _LastCategory; j++) {
503 			if (strncmp(cat_names[j], s,
504 			    strlen(cat_names[j])) == 0) {
505 				lcs[j] = s + strlen(cat_names[j]);
506 			}
507 		}
508 		if (strncmp("LANG=", s, strlen("LANG=")) == 0) {
509 			lang = s + strlen("LANG=");
510 		}
511 	}
512 
513 	if (lc_all && (*lc_all == '\0'))
514 		lc_all = NULL;
515 	if (lang && (*lang == '\0'))
516 		lang = NULL;
517 
518 	for (i = 0; i <= _LastCategory; i++) {
519 		if (lc_all != NULL) {
520 			lcs[i] = lc_all;
521 		} else if (lcs[i] != NULL) {
522 			lcs[i] = lcs[i];
523 		} else if (lang != NULL) {
524 			lcs[i] = lang;
525 		} else {
526 			lcs[i] = "C";
527 		}
528 		if ((i > 0) && (lcs[i] != lcs[i-1]))
529 			composite++;
530 
531 		len += 1 + strlen(lcs[i]);	/* 1 extra byte for '/' */
532 	}
533 
534 	if (composite == 0) {
535 		/* simple locale */
536 		pd_locale = safe_strdup(lcs[0]);
537 	} else {
538 		/* composite locale */
539 		pd_locale = safe_zalloc(len + 1);
540 		(void) snprintf(pd_locale, len + 1, "/%s/%s/%s/%s/%s/%s",
541 		    lcs[0], lcs[1], lcs[2], lcs[3], lcs[4], lcs[5]);
542 	}
543 	datap->pd_locale = pd_locale;
544 }
545 
546 /*
547  * Pull a string from the victim, regardless of size; this routine allocates
548  * memory for the string which must be freed by the caller.
549  */
550 static char *
551 extract_string(pargs_data_t *datap, uintptr_t addr)
552 {
553 	int size = EXTRACT_BUFSZ;
554 	char *result;
555 
556 	result = safe_zalloc(size);
557 
558 	for (;;) {
559 		if (Pread_string(datap->pd_proc, result, size, addr) < 0) {
560 			free(result);
561 			return (NULL);
562 		} else if (strlen(result) == (size - 1)) {
563 			free(result);
564 			size *= 2;
565 			result = safe_zalloc(size);
566 		} else {
567 			break;
568 		}
569 	}
570 	return (result);
571 }
572 
573 /*
574  * Utility function to read an array of pointers from the victim, adjusting
575  * for victim data model; returns the number of bytes successfully read.
576  */
577 static ssize_t
578 read_ptr_array(pargs_data_t *datap, uintptr_t offset, uintptr_t *buf,
579     size_t nelems)
580 {
581 	ssize_t res;
582 
583 	if (dmodel == PR_MODEL_NATIVE) {
584 		res = Pread(datap->pd_proc, buf, nelems * sizeof (uintptr_t),
585 		    offset);
586 	} else {
587 		int i;
588 		uint32_t *arr32 = safe_zalloc(nelems * sizeof (uint32_t));
589 
590 		res = Pread(datap->pd_proc, arr32, nelems * sizeof (uint32_t),
591 		    offset);
592 		if (res > 0) {
593 			for (i = 0; i < nelems; i++)
594 				buf[i] = arr32[i];
595 		}
596 		free(arr32);
597 	}
598 	return (res);
599 }
600 
601 /*
602  * Extract the argv array from the victim; store the pointer values in
603  * datap->pd_argv and the extracted strings in datap->pd_argv_strs.
604  */
605 static void
606 get_args(pargs_data_t *datap)
607 {
608 	size_t argc = datap->pd_psinfo->pr_argc;
609 	uintptr_t argvoff = datap->pd_psinfo->pr_argv;
610 	int i;
611 
612 	datap->pd_argc = argc;
613 	datap->pd_argv = safe_zalloc(argc * sizeof (uintptr_t));
614 
615 	if (read_ptr_array(datap, argvoff, datap->pd_argv, argc) <= 0) {
616 		free(datap->pd_argv);
617 		datap->pd_argv = NULL;
618 		return;
619 	}
620 
621 	datap->pd_argv_strs = safe_zalloc(argc * sizeof (char *));
622 	for (i = 0; i < argc; i++) {
623 		if (datap->pd_argv[i] == 0)
624 			continue;
625 		datap->pd_argv_strs[i] = extract_string(datap,
626 		    datap->pd_argv[i]);
627 	}
628 }
629 
630 /*ARGSUSED*/
631 static int
632 build_env(void *data, struct ps_prochandle *pr, uintptr_t addr, const char *str)
633 {
634 	pargs_data_t *datap = data;
635 
636 	if (datap->pd_envp != NULL) {
637 		datap->pd_envp[datap->pd_envc] = addr;
638 		if (str == NULL)
639 			datap->pd_envp_strs[datap->pd_envc] = NULL;
640 		else
641 			datap->pd_envp_strs[datap->pd_envc] = strdup(str);
642 	}
643 
644 	datap->pd_envc++;
645 
646 	return (0);
647 }
648 
649 static void
650 get_env(pargs_data_t *datap)
651 {
652 	struct ps_prochandle *pr = datap->pd_proc;
653 
654 	datap->pd_envc = 0;
655 	(void) Penv_iter(pr, build_env, datap);
656 
657 	datap->pd_envp = safe_zalloc(sizeof (uintptr_t) * datap->pd_envc);
658 	datap->pd_envp_strs = safe_zalloc(sizeof (char *) * datap->pd_envc);
659 
660 	datap->pd_envc = 0;
661 	(void) Penv_iter(pr, build_env, datap);
662 }
663 
664 /*
665  * The following at_* routines are used to decode data from the aux vector.
666  */
667 
668 /*ARGSUSED*/
669 static void
670 at_null(long val, char *instr, size_t n, char *str)
671 {
672 	str[0] = '\0';
673 }
674 
675 /*ARGSUSED*/
676 static void
677 at_str(long val, char *instr, size_t n, char *str)
678 {
679 	str[0] = '\0';
680 	if (instr != NULL) {
681 		(void) strlcpy(str, instr, n);
682 	}
683 }
684 
685 /*
686  * Note: Don't forget to add a corresponding case to isainfo(1).
687  */
688 
689 #define	FMT_AV(s, n, hwcap, mask, name)				\
690 	if ((hwcap) & (mask)) 					\
691 		(void) snprintf(s, n, "%s" name " | ", s)
692 
693 /*ARGSUSED*/
694 static void
695 at_hwcap(long val, char *instr, size_t n, char *str)
696 {
697 #if defined(__sparc) || defined(__sparcv9)
698 	(void) hwcap_1_val2str(val, str, n, CAP_FMT_PIPSPACE, EM_SPARC);
699 
700 #elif defined(__i386) || defined(__amd64)
701 	(void) hwcap_1_val2str(val, str, n, CAP_FMT_PIPSPACE, EM_386);
702 #else
703 #error	"port me"
704 #endif
705 }
706 
707 /*ARGSUSED*/
708 static void
709 at_uid(long val, char *instr, size_t n, char *str)
710 {
711 	struct passwd *pw = getpwuid((uid_t)val);
712 
713 	if ((pw == NULL) || (pw->pw_name == NULL))
714 		str[0] = '\0';
715 	else
716 		(void) snprintf(str, n, "%lu(%s)", val, pw->pw_name);
717 }
718 
719 
720 /*ARGSUSED*/
721 static void
722 at_gid(long val, char *instr, size_t n, char *str)
723 {
724 	struct group *gr = getgrgid((gid_t)val);
725 
726 	if ((gr == NULL) || (gr->gr_name == NULL))
727 		str[0] = '\0';
728 	else
729 		(void) snprintf(str, n, "%lu(%s)", val, gr->gr_name);
730 }
731 
732 static struct auxfl {
733 	int af_flag;
734 	const char *af_name;
735 } auxfl[] = {
736 	{ AF_SUN_SETUGID,	"setugid" },
737 };
738 
739 /*ARGSUSED*/
740 static void
741 at_flags(long val, char *instr, size_t n, char *str)
742 {
743 	int i;
744 
745 	*str = '\0';
746 
747 	for (i = 0; i < sizeof (auxfl)/sizeof (struct auxfl); i++) {
748 		if ((val & auxfl[i].af_flag) != 0) {
749 			if (*str != '\0')
750 				(void) strlcat(str, ",", n);
751 			(void) strlcat(str, auxfl[i].af_name, n);
752 		}
753 	}
754 }
755 
756 #define	MAX_AT_NAME_LEN	15
757 
758 struct aux_id {
759 	int aux_type;
760 	const char *aux_name;
761 	void (*aux_decode)(long, char *, size_t, char *);
762 };
763 
764 static struct aux_id aux_arr[] = {
765 	{ AT_NULL,		"AT_NULL",		at_null	},
766 	{ AT_IGNORE,		"AT_IGNORE",		at_null	},
767 	{ AT_EXECFD,		"AT_EXECFD",		at_null	},
768 	{ AT_PHDR,		"AT_PHDR",		at_null	},
769 	{ AT_PHENT,		"AT_PHENT",		at_null	},
770 	{ AT_PHNUM,		"AT_PHNUM",		at_null	},
771 	{ AT_PAGESZ,		"AT_PAGESZ",		at_null	},
772 	{ AT_BASE,		"AT_BASE",		at_null	},
773 	{ AT_FLAGS,		"AT_FLAGS",		at_null	},
774 	{ AT_ENTRY,		"AT_ENTRY",		at_null	},
775 	{ AT_SUN_UID,		"AT_SUN_UID",		at_uid	},
776 	{ AT_SUN_RUID,		"AT_SUN_RUID",		at_uid	},
777 	{ AT_SUN_GID,		"AT_SUN_GID",		at_gid	},
778 	{ AT_SUN_RGID,		"AT_SUN_RGID",		at_gid	},
779 	{ AT_SUN_LDELF,		"AT_SUN_LDELF",		at_null	},
780 	{ AT_SUN_LDSHDR,	"AT_SUN_LDSHDR",	at_null	},
781 	{ AT_SUN_LDNAME,	"AT_SUN_LDNAME",	at_null	},
782 	{ AT_SUN_LPAGESZ,	"AT_SUN_LPAGESZ",	at_null	},
783 	{ AT_SUN_PLATFORM,	"AT_SUN_PLATFORM",	at_str	},
784 	{ AT_SUN_EXECNAME,	"AT_SUN_EXECNAME",	at_str	},
785 	{ AT_SUN_HWCAP,		"AT_SUN_HWCAP",		at_hwcap },
786 	{ AT_SUN_IFLUSH,	"AT_SUN_IFLUSH",	at_null	},
787 	{ AT_SUN_CPU,		"AT_SUN_CPU",		at_null	},
788 	{ AT_SUN_MMU,		"AT_SUN_MMU",		at_null	},
789 	{ AT_SUN_LDDATA,	"AT_SUN_LDDATA",	at_null	},
790 	{ AT_SUN_AUXFLAGS,	"AT_SUN_AUXFLAGS",	at_flags },
791 };
792 
793 #define	N_AT_ENTS (sizeof (aux_arr) / sizeof (struct aux_id))
794 
795 /*
796  * Return the aux_id entry for the given aux type; returns NULL if not found.
797  */
798 static struct aux_id *
799 aux_find(int type)
800 {
801 	int i;
802 
803 	for (i = 0; i < N_AT_ENTS; i++) {
804 		if (type == aux_arr[i].aux_type)
805 			return (&aux_arr[i]);
806 	}
807 
808 	return (NULL);
809 }
810 
811 static void
812 get_auxv(pargs_data_t *datap)
813 {
814 	int i;
815 	const auxv_t *auxvp;
816 
817 	/*
818 	 * Fetch the aux vector from the target process.
819 	 */
820 	if (ps_pauxv(datap->pd_proc, &auxvp) != PS_OK)
821 		return;
822 
823 	for (i = 0; auxvp[i].a_type != AT_NULL; i++)
824 		continue;
825 
826 	datap->pd_auxc = i;
827 	datap->pd_auxv = safe_zalloc(i * sizeof (auxv_t));
828 	bcopy(auxvp, datap->pd_auxv, i * sizeof (auxv_t));
829 
830 	datap->pd_auxv_strs = safe_zalloc(datap->pd_auxc * sizeof (char *));
831 	for (i = 0; i < datap->pd_auxc; i++) {
832 		struct aux_id *aux = aux_find(datap->pd_auxv[i].a_type);
833 
834 		/*
835 		 * Grab strings for those entries which have a string-decoder.
836 		 */
837 		if ((aux != NULL) && (aux->aux_decode == at_str)) {
838 			datap->pd_auxv_strs[i] =
839 			    extract_string(datap, datap->pd_auxv[i].a_un.a_val);
840 		}
841 	}
842 }
843 
844 /*
845  * Prepare to convert characters in the victim's character set into user's
846  * character set.
847  */
848 static void
849 setup_conversions(pargs_data_t *datap, int *diflocale)
850 {
851 	char *mylocale = NULL, *mycharset = NULL;
852 	char *targetlocale = NULL, *targetcharset = NULL;
853 
854 	mycharset = safe_strdup(nl_langinfo(CODESET));
855 
856 	mylocale = setlocale(LC_CTYPE, NULL);
857 	if ((mylocale == NULL) || (strcmp(mylocale, "") == 0))
858 		mylocale = "C";
859 	mylocale = safe_strdup(mylocale);
860 
861 	if (datap->pd_conv_flags & CONV_STRICT_ASCII)
862 		goto done;
863 
864 	/*
865 	 * If the target's locale is "C" or "POSIX", go fast.
866 	 */
867 	if ((strcmp(datap->pd_locale, "C") == 0) ||
868 	    (strcmp(datap->pd_locale, "POSIX") == 0)) {
869 		datap->pd_conv_flags |= CONV_STRICT_ASCII;
870 		goto done;
871 	}
872 
873 	/*
874 	 * Switch to the victim's locale, and discover its character set.
875 	 */
876 	if (setlocale(LC_ALL, datap->pd_locale) == NULL) {
877 		(void) fprintf(stderr,
878 		    "%s: Couldn't determine locale of target process.\n",
879 		    command);
880 		(void) fprintf(stderr,
881 		    "%s: Some strings may not be displayed properly.\n",
882 		    command);
883 		goto done;
884 	}
885 
886 	/*
887 	 * Get LC_CTYPE part of target's locale, and its codeset.
888 	 */
889 	targetlocale = safe_strdup(setlocale(LC_CTYPE, NULL));
890 	targetcharset = safe_strdup(nl_langinfo(CODESET));
891 
892 	/*
893 	 * Now go fully back to the pargs user's locale.
894 	 */
895 	(void) setlocale(LC_ALL, "");
896 
897 	/*
898 	 * It's safe to bail here if the lc_ctype of the locales are the
899 	 * same-- we know that their encodings and characters sets are the same.
900 	 */
901 	if (strcmp(targetlocale, mylocale) == 0)
902 		goto done;
903 
904 	*diflocale = 1;
905 
906 	/*
907 	 * If the codeset of the victim matches our codeset then iconv need
908 	 * not be involved.
909 	 */
910 	if (strcmp(mycharset, targetcharset) == 0)
911 		goto done;
912 
913 	if ((datap->pd_iconv = iconv_open(mycharset, targetcharset))
914 	    == (iconv_t)-1) {
915 		/*
916 		 * EINVAL indicates there was no conversion available
917 		 * from victim charset to mycharset
918 		 */
919 		if (errno != EINVAL) {
920 			(void) fprintf(stderr,
921 			    "%s: failed to initialize iconv: %s\n",
922 			    command, strerror(errno));
923 			exit(1);
924 		}
925 		datap->pd_conv_flags |= CONV_STRICT_ASCII;
926 	} else {
927 		datap->pd_conv_flags |= CONV_USE_ICONV;
928 	}
929 done:
930 	free(mycharset);
931 	free(mylocale);
932 	free(targetcharset);
933 	free(targetlocale);
934 }
935 
936 static void
937 cleanup_conversions(pargs_data_t *datap)
938 {
939 	if (datap->pd_conv_flags & CONV_USE_ICONV) {
940 		(void) iconv_close(datap->pd_iconv);
941 	}
942 }
943 
944 static char *
945 convert_run_iconv(pargs_data_t *datap, const char *str)
946 {
947 	size_t inleft, outleft, bufsz = 64;
948 	char *outstr, *outstrptr;
949 	const char *instrptr;
950 
951 	for (;;) {
952 		outstrptr = outstr = safe_zalloc(bufsz + 1);
953 		outleft = bufsz;
954 
955 		/*
956 		 * Generate the "initial shift state" sequence, placing that
957 		 * at the head of the string.
958 		 */
959 		inleft = 0;
960 		(void) iconv(datap->pd_iconv, NULL, &inleft,
961 		    &outstrptr, &outleft);
962 
963 		inleft = strlen(str);
964 		instrptr = str;
965 		if (iconv(datap->pd_iconv, &instrptr, &inleft, &outstrptr,
966 		    &outleft) != (size_t)-1) {
967 			/*
968 			 * Outstr must be null terminated upon exit from
969 			 * iconv().
970 			 */
971 			*(outstr + (bufsz - outleft)) = '\0';
972 			break;
973 		} else if (errno == E2BIG) {
974 			bufsz *= 2;
975 			free(outstr);
976 		} else if ((errno == EILSEQ) || (errno == EINVAL)) {
977 			free(outstr);
978 			return (NULL);
979 		} else {
980 			/*
981 			 * iconv() could in theory return EBADF, but that
982 			 * shouldn't happen.
983 			 */
984 			(void) fprintf(stderr,
985 			    "%s: iconv(3C) failed unexpectedly: %s\n",
986 			    command, strerror(errno));
987 
988 			exit(1);
989 		}
990 	}
991 	return (outstr);
992 }
993 
994 /*
995  * Returns a freshly allocated string converted to the local character set,
996  * removed of unprintable characters.
997  */
998 static char *
999 convert_str(pargs_data_t *datap, const char *str, int *unprintable)
1000 {
1001 	char *retstr, *tmp;
1002 
1003 	if (datap->pd_conv_flags & CONV_STRICT_ASCII) {
1004 		retstr = unctrl_str_strict_ascii(str, 1, unprintable);
1005 		return (retstr);
1006 	}
1007 
1008 	if ((datap->pd_conv_flags & CONV_USE_ICONV) == 0) {
1009 		/*
1010 		 * If we aren't using iconv(), convert control chars in
1011 		 * the string in pargs' locale, since that is the display
1012 		 * locale.
1013 		 */
1014 		retstr = unctrl_str(str, 1, unprintable);
1015 		return (retstr);
1016 	}
1017 
1018 	/*
1019 	 * The logic here is a bit (ahem) tricky.  Start by converting
1020 	 * unprintable characters *in the target's locale*.  This should
1021 	 * eliminate a variety of unprintable or illegal characters-- in
1022 	 * short, it should leave us with something which iconv() won't
1023 	 * have trouble with.
1024 	 *
1025 	 * After allowing iconv to convert characters as needed, run unctrl
1026 	 * again in pargs' locale-- This time to make sure that any
1027 	 * characters which aren't printable according to the *current*
1028 	 * locale (independent of the current codeset) get taken care of.
1029 	 * Without this second stage, we might (for example) fail to
1030 	 * properly handle characters converted into the 646 character set
1031 	 * (which are 8-bits wide), but which must be displayed in the C
1032 	 * locale (which uses 646, but whose printable characters are a
1033 	 * subset of the 7-bit characters).
1034 	 *
1035 	 * Note that assuming the victim's locale using LC_ALL will be
1036 	 * problematic when pargs' messages are internationalized in the
1037 	 * future (and it calls textdomain(3C)).  In this case, any
1038 	 * error message fprintf'd in unctrl_str() will be in the wrong
1039 	 * LC_MESSAGES class.  We'll cross that bridge when we come to it.
1040 	 */
1041 	(void) setlocale(LC_ALL, datap->pd_locale);
1042 	retstr = unctrl_str(str, 1, unprintable);
1043 	(void) setlocale(LC_ALL, "");
1044 
1045 	tmp = retstr;
1046 	if ((retstr = convert_run_iconv(datap, retstr)) == NULL) {
1047 		/*
1048 		 * In this (rare but real) case, the iconv() failed even
1049 		 * though we unctrl'd the string.  Treat the original string
1050 		 * (str) as a C locale string and strip it that way.
1051 		 */
1052 		free(tmp);
1053 		return (unctrl_str_strict_ascii(str, 0, unprintable));
1054 	}
1055 
1056 	free(tmp);
1057 	tmp = retstr;
1058 	/*
1059 	 * Run unctrl_str, but make sure not to escape \ characters, which
1060 	 * may have resulted from the first round of unctrl.
1061 	 */
1062 	retstr = unctrl_str(retstr, 0, unprintable);
1063 	free(tmp);
1064 	return (retstr);
1065 }
1066 
1067 
1068 static void
1069 convert_array(pargs_data_t *datap, char **arr, size_t count, int *unprintable)
1070 {
1071 	int i;
1072 	char *tmp;
1073 
1074 	if (arr == NULL)
1075 		return;
1076 
1077 	for (i = 0; i < count; i++) {
1078 		if ((tmp = arr[i]) == NULL)
1079 			continue;
1080 		arr[i] = convert_str(datap, arr[i], unprintable);
1081 		free(tmp);
1082 	}
1083 }
1084 
1085 /*
1086  * Free data allocated during the gathering phase.
1087  */
1088 static void
1089 free_data(pargs_data_t *datap)
1090 {
1091 	int i;
1092 
1093 	if (datap->pd_argv) {
1094 		for (i = 0; i < datap->pd_argc; i++) {
1095 			if (datap->pd_argv_strs[i] != NULL)
1096 				free(datap->pd_argv_strs[i]);
1097 		}
1098 		free(datap->pd_argv);
1099 		free(datap->pd_argv_strs);
1100 	}
1101 
1102 	if (datap->pd_envp) {
1103 		for (i = 0; i < datap->pd_envc; i++) {
1104 			if (datap->pd_envp_strs[i] != NULL)
1105 				free(datap->pd_envp_strs[i]);
1106 		}
1107 		free(datap->pd_envp);
1108 		free(datap->pd_envp_strs);
1109 	}
1110 
1111 	if (datap->pd_auxv) {
1112 		for (i = 0; i < datap->pd_auxc; i++) {
1113 			if (datap->pd_auxv_strs[i] != NULL)
1114 				free(datap->pd_auxv_strs[i]);
1115 		}
1116 		free(datap->pd_auxv);
1117 		free(datap->pd_auxv_strs);
1118 	}
1119 }
1120 
1121 static void
1122 print_args(pargs_data_t *datap)
1123 {
1124 	int i;
1125 
1126 	if (datap->pd_argv == NULL) {
1127 		(void) fprintf(stderr, "%s: failed to read argv[]\n", command);
1128 		return;
1129 	}
1130 
1131 	for (i = 0; i < datap->pd_argc; i++) {
1132 		(void) printf("argv[%d]: ", i);
1133 		if (datap->pd_argv[i] == NULL) {
1134 			(void) printf("<NULL>\n");
1135 		} else if (datap->pd_argv_strs[i] == NULL) {
1136 			(void) printf("<0x%0*lx>\n",
1137 			    (dmodel == PR_MODEL_LP64)? 16 : 8,
1138 			    (long)datap->pd_argv[i]);
1139 		} else {
1140 			(void) printf("%s\n", datap->pd_argv_strs[i]);
1141 		}
1142 	}
1143 }
1144 
1145 static void
1146 print_env(pargs_data_t *datap)
1147 {
1148 	int i;
1149 
1150 	if (datap->pd_envp == NULL) {
1151 		(void) fprintf(stderr, "%s: failed to read envp[]\n", command);
1152 		return;
1153 	}
1154 
1155 	for (i = 0; i < datap->pd_envc; i++) {
1156 		(void) printf("envp[%d]: ", i);
1157 		if (datap->pd_envp[i] == 0) {
1158 			break;
1159 		} else if (datap->pd_envp_strs[i] == NULL) {
1160 			(void) printf("<0x%0*lx>\n",
1161 			    (dmodel == PR_MODEL_LP64)? 16 : 8,
1162 			    (long)datap->pd_envp[i]);
1163 		} else {
1164 			(void) printf("%s\n", datap->pd_envp_strs[i]);
1165 		}
1166 	}
1167 }
1168 
1169 static int
1170 print_cmdline(pargs_data_t *datap)
1171 {
1172 	int i;
1173 
1174 	/*
1175 	 * Go through and check to see if we have valid data.  If not, print
1176 	 * an error message and bail.
1177 	 */
1178 	for (i = 0; i < datap->pd_argc; i++) {
1179 		if (datap->pd_argv[i] == NULL ||
1180 		    datap->pd_argv_strs[i] == NULL) {
1181 			(void) fprintf(stderr, "%s: target has corrupted "
1182 			    "argument list\n", command);
1183 			return (1);
1184 		}
1185 
1186 		datap->pd_argv_strs[i] =
1187 		    quote_string(datap, datap->pd_argv_strs[i]);
1188 	}
1189 
1190 	if (datap->pd_execname == NULL) {
1191 		(void) fprintf(stderr, "%s: cannot determine name of "
1192 		    "executable\n", command);
1193 		return (1);
1194 	}
1195 
1196 	(void) printf("%s ", datap->pd_execname);
1197 
1198 	for (i = 1; i < datap->pd_argc; i++)
1199 		(void) printf("%s ", datap->pd_argv_strs[i]);
1200 
1201 	(void) printf("\n");
1202 
1203 	return (0);
1204 }
1205 
1206 static void
1207 print_auxv(pargs_data_t *datap)
1208 {
1209 	int i;
1210 	const auxv_t *pa;
1211 
1212 	/*
1213 	 * Print the names and values of all the aux vector entries.
1214 	 */
1215 	for (i = 0; i < datap->pd_auxc; i++) {
1216 		char type[32];
1217 		char decode[PATH_MAX];
1218 		struct aux_id *aux;
1219 		long v;
1220 		pa = &datap->pd_auxv[i];
1221 
1222 		aux = aux_find(pa->a_type);
1223 		v = (long)pa->a_un.a_val;
1224 
1225 		if (aux != NULL) {
1226 			/*
1227 			 * Fetch aux vector type string and decoded
1228 			 * representation of the value.
1229 			 */
1230 			(void) strlcpy(type, aux->aux_name, sizeof (type));
1231 			aux->aux_decode(v, datap->pd_auxv_strs[i],
1232 			    sizeof (decode), decode);
1233 		} else {
1234 			(void) snprintf(type, sizeof (type), "%d", pa->a_type);
1235 			decode[0] = '\0';
1236 		}
1237 
1238 		(void) printf("%-*s 0x%0*lx %s\n", MAX_AT_NAME_LEN, type,
1239 		    (dmodel == PR_MODEL_LP64)? 16 : 8, v, decode);
1240 	}
1241 }
1242 
1243 int
1244 main(int argc, char *argv[])
1245 {
1246 	int aflag = 0, cflag = 0, eflag = 0, xflag = 0, lflag = 0;
1247 	int errflg = 0, retc = 0;
1248 	int opt;
1249 	int error = 1;
1250 	core_content_t content = 0;
1251 
1252 	(void) setlocale(LC_ALL, "");
1253 
1254 	if ((command = strrchr(argv[0], '/')) != NULL)
1255 		command++;
1256 	else
1257 		command = argv[0];
1258 
1259 	while ((opt = getopt(argc, argv, "acelxF")) != EOF) {
1260 		switch (opt) {
1261 		case 'a':		/* show process arguments */
1262 			content |= CC_CONTENT_STACK;
1263 			aflag++;
1264 			break;
1265 		case 'c':		/* force 7-bit ascii */
1266 			cflag++;
1267 			break;
1268 		case 'e':		/* show environment variables */
1269 			content |= CC_CONTENT_STACK;
1270 			eflag++;
1271 			break;
1272 		case 'l':
1273 			lflag++;
1274 			aflag++;	/* -l implies -a */
1275 			break;
1276 		case 'x':		/* show aux vector entries */
1277 			xflag++;
1278 			break;
1279 		case 'F':
1280 			/*
1281 			 * Since we open the process read-only, there is no need
1282 			 * for the -F flag.  It's a documented flag, so we
1283 			 * consume it silently.
1284 			 */
1285 			break;
1286 		default:
1287 			errflg++;
1288 			break;
1289 		}
1290 	}
1291 
1292 	/* -a is the default if no options are specified */
1293 	if ((aflag + eflag + xflag + lflag) == 0) {
1294 		aflag++;
1295 		content |= CC_CONTENT_STACK;
1296 	}
1297 
1298 	/* -l cannot be used with the -x or -e flags */
1299 	if (lflag && (xflag || eflag)) {
1300 		(void) fprintf(stderr, "-l is incompatible with -x and -e\n");
1301 		errflg++;
1302 	}
1303 
1304 	argc -= optind;
1305 	argv += optind;
1306 
1307 	if (errflg || argc <= 0) {
1308 		(void) fprintf(stderr,
1309 		    "usage:  %s [-acexF] { pid | core } ...\n"
1310 		    "  (show process arguments and environment)\n"
1311 		    "  -a: show process arguments (default)\n"
1312 		    "  -c: interpret characters as 7-bit ascii regardless of "
1313 		    "locale\n"
1314 		    "  -e: show environment variables\n"
1315 		    "  -l: display arguments as command line\n"
1316 		    "  -x: show aux vector entries\n"
1317 		    "  -F: force grabbing of the target process\n", command);
1318 		return (2);
1319 	}
1320 
1321 	while (argc-- > 0) {
1322 		char *arg;
1323 		int gret, r;
1324 		psinfo_t psinfo;
1325 		char *psargs_conv;
1326 		struct ps_prochandle *Pr;
1327 		pargs_data_t datap;
1328 		char *info;
1329 		size_t info_sz;
1330 		int pstate;
1331 		char execname[PATH_MAX];
1332 		int unprintable;
1333 		int diflocale;
1334 
1335 		(void) fflush(stdout);
1336 		arg = *argv++;
1337 
1338 		/*
1339 		 * Suppress extra blanks lines if we've encountered processes
1340 		 * which can't be opened.
1341 		 */
1342 		if (error == 0) {
1343 			(void) printf("\n");
1344 		}
1345 		error = 0;
1346 
1347 		/*
1348 		 * First grab just the psinfo information, in case this
1349 		 * process is a zombie (in which case proc_arg_grab() will
1350 		 * fail).  If so, print a nice message and continue.
1351 		 */
1352 		if (proc_arg_psinfo(arg, PR_ARG_ANY, &psinfo,
1353 		    &gret) == -1) {
1354 			(void) fprintf(stderr, "%s: cannot examine %s: %s\n",
1355 			    command, arg, Pgrab_error(gret));
1356 			retc++;
1357 			error = 1;
1358 			continue;
1359 		}
1360 
1361 		if (psinfo.pr_nlwp == 0) {
1362 			(void) printf("%d: <defunct>\n", (int)psinfo.pr_pid);
1363 			continue;
1364 		}
1365 
1366 		/*
1367 		 * If process is a "system" process (like pageout), just
1368 		 * print its psargs and continue on.
1369 		 */
1370 		if (psinfo.pr_size == 0 && psinfo.pr_rssize == 0) {
1371 			proc_unctrl_psinfo(&psinfo);
1372 			if (!lflag)
1373 				(void) printf("%d: ", (int)psinfo.pr_pid);
1374 			(void) printf("%s\n", psinfo.pr_psargs);
1375 			continue;
1376 		}
1377 
1378 		/*
1379 		 * Open the process readonly, since we do not need to write to
1380 		 * the control file.
1381 		 */
1382 		if ((Pr = proc_arg_grab(arg, PR_ARG_ANY, PGRAB_RDONLY,
1383 		    &gret)) == NULL) {
1384 			(void) fprintf(stderr, "%s: cannot examine %s: %s\n",
1385 			    command, arg, Pgrab_error(gret));
1386 			retc++;
1387 			error = 1;
1388 			continue;
1389 		}
1390 
1391 		pstate = Pstate(Pr);
1392 
1393 		if (pstate == PS_DEAD &&
1394 		    (Pcontent(Pr) & content) != content) {
1395 			(void) fprintf(stderr, "%s: core '%s' has "
1396 			    "insufficient content\n", command, arg);
1397 			retc++;
1398 			continue;
1399 		}
1400 
1401 		/*
1402 		 * If malloc() fails, we return here so that we can let go
1403 		 * of the victim, restore our locale, print a message,
1404 		 * then exit.
1405 		 */
1406 		if ((r = setjmp(env)) != 0) {
1407 			Prelease(Pr, 0);
1408 			(void) setlocale(LC_ALL, "");
1409 			(void) fprintf(stderr, "%s: out of memory: %s\n",
1410 			    command, strerror(r));
1411 			return (1);
1412 		}
1413 
1414 		dmodel = Pstatus(Pr)->pr_dmodel;
1415 		bzero(&datap, sizeof (datap));
1416 		bcopy(Ppsinfo(Pr), &psinfo, sizeof (psinfo_t));
1417 		datap.pd_proc = Pr;
1418 		datap.pd_psinfo = &psinfo;
1419 
1420 		if (cflag)
1421 			datap.pd_conv_flags |= CONV_STRICT_ASCII;
1422 
1423 		/*
1424 		 * Strip control characters, then record process summary in
1425 		 * a buffer, since we don't want to print anything out until
1426 		 * after we release the process.
1427 		 */
1428 
1429 		/*
1430 		 * The process is neither a system process nor defunct.
1431 		 *
1432 		 * Do printing and post-processing (like name lookups) after
1433 		 * gathering the raw data from the process and releasing it.
1434 		 * This way, we don't deadlock on (for example) name lookup
1435 		 * if we grabbed the nscd and do 'pargs -x'.
1436 		 *
1437 		 * We always fetch the environment of the target, so that we
1438 		 * can make an educated guess about its locale.
1439 		 */
1440 		get_env(&datap);
1441 		if (aflag != 0)
1442 			get_args(&datap);
1443 		if (xflag != 0)
1444 			get_auxv(&datap);
1445 
1446 		/*
1447 		 * If malloc() fails after this poiint, we return here to
1448 		 * restore our locale and print a message.  If we don't
1449 		 * reset this, we might erroneously try to Prelease a process
1450 		 * twice.
1451 		 */
1452 		if ((r = setjmp(env)) != 0) {
1453 			(void) setlocale(LC_ALL, "");
1454 			(void) fprintf(stderr, "%s: out of memory: %s\n",
1455 			    command, strerror(r));
1456 			return (1);
1457 		}
1458 
1459 		/*
1460 		 * For the -l option, we need a proper name for this executable
1461 		 * before we release it.
1462 		 */
1463 		if (lflag)
1464 			datap.pd_execname = Pexecname(Pr, execname,
1465 			    sizeof (execname));
1466 
1467 		Prelease(Pr, 0);
1468 
1469 		/*
1470 		 * Crawl through the environment to determine the locale of
1471 		 * the target.
1472 		 */
1473 		lookup_locale(&datap);
1474 		diflocale = 0;
1475 		setup_conversions(&datap, &diflocale);
1476 
1477 		if (lflag != 0) {
1478 			unprintable = 0;
1479 			convert_array(&datap, datap.pd_argv_strs,
1480 			    datap.pd_argc, &unprintable);
1481 			if (diflocale)
1482 				(void) fprintf(stderr, "%s: Warning, target "
1483 				    "locale differs from current locale\n",
1484 				    command);
1485 			else if (unprintable)
1486 				(void) fprintf(stderr, "%s: Warning, command "
1487 				    "line contains unprintable characters\n",
1488 				    command);
1489 
1490 			retc += print_cmdline(&datap);
1491 		} else {
1492 			psargs_conv = convert_str(&datap, psinfo.pr_psargs,
1493 			    &unprintable);
1494 			info_sz = strlen(psargs_conv) + MAXPATHLEN + 32 + 1;
1495 			info = malloc(info_sz);
1496 			if (pstate == PS_DEAD) {
1497 				(void) snprintf(info, info_sz,
1498 				    "core '%s' of %d:\t%s\n",
1499 				    arg, (int)psinfo.pr_pid, psargs_conv);
1500 			} else {
1501 				(void) snprintf(info, info_sz, "%d:\t%s\n",
1502 				    (int)psinfo.pr_pid, psargs_conv);
1503 			}
1504 			(void) printf("%s", info);
1505 			free(info);
1506 			free(psargs_conv);
1507 
1508 			if (aflag != 0) {
1509 				convert_array(&datap, datap.pd_argv_strs,
1510 				    datap.pd_argc, &unprintable);
1511 				print_args(&datap);
1512 				if (eflag || xflag)
1513 					(void) printf("\n");
1514 			}
1515 
1516 			if (eflag != 0) {
1517 				convert_array(&datap, datap.pd_envp_strs,
1518 				    datap.pd_envc, &unprintable);
1519 				print_env(&datap);
1520 				if (xflag)
1521 					(void) printf("\n");
1522 			}
1523 
1524 			if (xflag != 0) {
1525 				convert_array(&datap, datap.pd_auxv_strs,
1526 				    datap.pd_auxc, &unprintable);
1527 				print_auxv(&datap);
1528 			}
1529 		}
1530 
1531 		cleanup_conversions(&datap);
1532 		free_data(&datap);
1533 	}
1534 
1535 	return (retc != 0 ? 1 : 0);
1536 }
1537