pmap.c 30.9 KB
Newer Older
albert's avatar
albert committed
1
/*
2 3 4 5 6 7 8 9 10
 * pmap.c - print process memory mapping
 * Copyright 2002 Albert Cahalan
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
albert's avatar
albert committed
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 13 14 15 16 17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
albert's avatar
albert committed
18 19
 */

csmall's avatar
csmall committed
20
#include <ctype.h>
21
#include <errno.h>
albert's avatar
albert committed
22
#include <fcntl.h>
23 24 25
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
albert's avatar
albert committed
26
#include <string.h>
27 28
#include <sys/ipc.h>
#include <sys/shm.h>
29 30 31
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
32
#include <assert.h>
33

Sami Kerola's avatar
Sami Kerola committed
34
#include "c.h"
35
#include "fileutils.h"
Sami Kerola's avatar
Sami Kerola committed
36
#include "nls.h"
37
#include "proc/escape.h"
38
#include "xalloc.h"
albert's avatar
albert committed
39 40
#include "proc/readproc.h"
#include "proc/version.h"
csmall's avatar
csmall committed
41

42 43 44 45
const char *nls_Address,
	   *nls_Offset,
	   *nls_Device,
	   *nls_Mapping,
46
	   *nls_Perm,
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
	   *nls_Inode,
	   *nls_Kbytes,
	   *nls_Mode,
	   *nls_RSS,
	   *nls_Dirty;

static void nls_initialize(void)
{
	setlocale (LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);

	/* these are the headings shared across all options,
	   though their widths when output might differ */
	nls_Address = _("Address");
	nls_Offset  = _("Offset");
	nls_Device  = _("Device");
	nls_Mapping = _("Mapping");

	/* these headings are used only by the -X/-XX options,
	   and are not derived literally from /proc/#/smaps */
68
	nls_Perm    = _("Perm");
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
	nls_Inode   = _("Inode");

	/* these are potentially used for options other than -X/-XX, */
	nls_Kbytes  = _("Kbytes");
	nls_Mode    = _("Mode");
	nls_RSS     = _("RSS");
	nls_Dirty   = _("Dirty");
}

static int justify_print(const char *str, int width, int right)
{
	if (width < 1)
		puts(str);
	else {
		int len = strlen(str);
		if (width < len) width = len;
		printf(right ? "%*.*s " : "%-*.*s ", width, width, str);
	}
	return width;
}
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

static int integer_width(unsigned KLONG number)
{
	int result;

	result = !(number > 0);
	while (number) {
		result++;
		number /= 10;
	}

	return result;
}


104
static void __attribute__ ((__noreturn__))
105
usage(FILE * out)
106
{
Sami Kerola's avatar
Sami Kerola committed
107
	fputs(USAGE_HEADER, out);
108
	fprintf(out,
Craig Small's avatar
Craig Small committed
109
		_(" %s [options] PID [PID ...]\n"), program_invocation_short_name);
Sami Kerola's avatar
Sami Kerola committed
110
	fputs(USAGE_OPTIONS, out);
111 112 113 114 115 116 117 118 119 120 121 122 123
	fputs(_(" -x, --extended              show details\n"), out);
	fputs(_(" -X                          show even more details\n"), out);
	fputs(_("            WARNING: format changes according to /proc/PID/smaps\n"), out);
	fputs(_(" -XX                         show everything the kernel provides\n"), out);
	fputs(_(" -c, --read-rc               read the default rc\n"), out);
	fputs(_(" -C, --read-rc-from=<file>   read the rc from file\n"), out);
	fputs(_(" -n, --create-rc             create new default rc\n"), out);
	fputs(_(" -N, --create-rc-to=<file>   create new rc to file\n"), out);
	fputs(_("            NOTE: pid arguments are not allowed with -n, -N\n"), out);
	fputs(_(" -d, --device                show the device format\n"), out);
	fputs(_(" -q, --quiet                 do not display header and footer\n"), out);
	fputs(_(" -p, --show-path             show path in the mapping\n"), out);
	fputs(_(" -A, --range=<low>[,<high>]  limit results to the given range\n"), out);
Sami Kerola's avatar
Sami Kerola committed
124 125 126 127
	fputs(USAGE_SEPARATOR, out);
	fputs(USAGE_HELP, out);
	fputs(USAGE_VERSION, out);
	fprintf(out, USAGE_MAN_TAIL("pmap(1)"));
128
	exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
csmall's avatar
csmall committed
129 130
}

131 132 133
static char mapbuf[1024];
static char cmdbuf[512];

134 135 136
static unsigned KLONG range_low;
static unsigned KLONG range_high = ~0ull;

137 138
static int c_option;
static int C_option;
139
static int d_option;
140 141
static int n_option;
static int N_option;
142
static int q_option;
143
static int x_option;
144
static int X_option;
albert's avatar
albert committed
145

146 147
static int map_desc_showpath;

148 149
static unsigned shm_minor = ~0u;

150 151 152 153
static void discover_shm_minor(void)
{
	void *addr;
	int shmid;
154
	char mapbuf_b[256];
155 156 157 158 159 160 161 162 163 164 165 166 167 168

	if (!freopen("/proc/self/maps", "r", stdin))
		return;

	/* create */
	shmid = shmget(IPC_PRIVATE, 42, IPC_CREAT | 0666);
	if (shmid == -1)
		/* failed; oh well */
		return;
	/* attach */
	addr = shmat(shmid, NULL, SHM_RDONLY);
	if (addr == (void *)-1)
		goto out_destroy;

169
	while (fgets(mapbuf_b, sizeof mapbuf_b, stdin)) {
170
		char perms[32];
171 172 173 174 175
		/* to clean up unprintables */
		char *tmp;
		unsigned KLONG start, end;
		unsigned long long file_offset, inode;
		unsigned dev_major, dev_minor;
176
		sscanf(mapbuf_b, "%" KLF "x-%" KLF "x %31s %llx %x:%x %llu", &start,
177
		       &end, perms, &file_offset, &dev_major, &dev_minor,
178
		       &inode);
179
		tmp = strchr(mapbuf_b, '\n');
180 181
		if (tmp)
			*tmp = '\0';
182
		tmp = mapbuf_b;
183 184 185 186 187 188 189 190 191
		while (*tmp) {
			if (!isprint(*tmp))
				*tmp = '?';
			tmp++;
		}
		if (start > (unsigned long)addr)
			continue;
		if (dev_major)
			continue;
192
		if (perms[3] != 's')
193
			continue;
194
		if (strstr(mapbuf_b, "/SYSV")) {
195 196 197 198 199 200
			shm_minor = dev_minor;
			break;
		}
	}

	if (shmdt(addr))
201
		perror(_("shared memory detach"));
202

203
out_destroy:
204
	if (shmctl(shmid, IPC_RMID, NULL) && errno != EINVAL)
205
		perror(_("shared memory remove"));
206 207

	return;
albert's avatar
albert committed
208 209
}

210
static char *mapping_name(proc_t * p, unsigned KLONG addr,
211
				unsigned KLONG len, const char *mapbuf_b,
212 213 214
				unsigned showpath, unsigned dev_major,
				unsigned dev_minor, unsigned long long inode)
{
215
	char *cp;
216

217
	if (!dev_major && dev_minor == shm_minor && strstr(mapbuf_b, "/SYSV")) {
218
		static char shmbuf[64];
219
		snprintf(shmbuf, sizeof shmbuf, "  [ shmid=0x%llx ]", inode);
220 221 222
		return shmbuf;
	}

223
	cp = strrchr(mapbuf_b, '/');
224 225
	if (cp) {
		if (showpath)
226
			return strchr(mapbuf_b, '/');
227 228 229
		return cp[1] ? cp + 1 : cp;
	}

230
	cp = strchr(mapbuf_b, '/');
231 232 233 234 235 236 237
	if (cp) {
		if (showpath)
			return cp;
		/* it WILL succeed */
		return strrchr(cp, '/') + 1;
	}

Sami Kerola's avatar
Sami Kerola committed
238
	cp = _("  [ anon ]");
239
	if ((p->start_stack >= addr) && (p->start_stack <= addr + len))
Sami Kerola's avatar
Sami Kerola committed
240
		cp = _("  [ stack ]");
241
	return cp;
albert's avatar
albert committed
242
}
albert's avatar
albert committed
243

244 245 246 247 248

#define DETAIL_LENGTH 32
#define DETL "31"		/* for format strings */
#define NUM_LENGTH 21		/* python says: len(str(2**64)) == 20 */
#define NUML "20"		/* for format strings */
249
#define VMFLAGS_LENGTH 81 /* There are 27 posible 2 character vmflags as of this patch */
250 251 252 253 254 255 256 257 258 259

struct listnode {
	char description[DETAIL_LENGTH];
	char value_str[NUM_LENGTH];
	unsigned KLONG value;
	unsigned KLONG total;
	int max_width;
	struct listnode *next;
};

260
static struct listnode *listhead=NULL, *listtail=NULL, *listnode;
261 262


263 264 265 266 267 268 269
struct cnf_listnode {
	char description[DETAIL_LENGTH];
	struct cnf_listnode *next;
};

static struct cnf_listnode *cnf_listhead=NULL, *cnf_listnode;

270
static int is_unimportant (const char *s)
271 272 273 274 275 276 277 278
{
	if (strcmp(s, "AnonHugePages") == 0) return 1;
	if (strcmp(s, "KernelPageSize") == 0) return 1;
	if (strcmp(s, "MMUPageSize") == 0) return 1;
	if (strcmp(s, "Shared_Dirty") == 0) return 1;
	if (strcmp(s, "Private_Dirty") == 0) return 1;
	if (strcmp(s, "Shared_Clean") == 0) return 1;
	if (strcmp(s, "Private_Clean") == 0) return 1;
279
	if (strcmp(s, "VmFlags") == 0) return 1;
280 281 282
	return 0;
}

283
/* check, whether we want to display the field or not */
284
static int is_enabled (const char *s)
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
{
	if (X_option == 1) return !is_unimportant(s);

	if (c_option) {  /* taking the list of disabled fields from the rc file */

		for (cnf_listnode = cnf_listhead; cnf_listnode; cnf_listnode = cnf_listnode -> next) {
			if (!strcmp(s, cnf_listnode -> description)) return 1;
		}
		return 0;

	}

	return 1;
}


301 302
static void print_extended_maps (FILE *f)
{
303
	char perms[DETAIL_LENGTH], map_desc[128],
304 305 306
	     detail_desc[DETAIL_LENGTH], value_str[NUM_LENGTH],
	     start[NUM_LENGTH], end[NUM_LENGTH],
	     offset[NUM_LENGTH], inode[NUM_LENGTH],
307
	     dev[64], vmflags[VMFLAGS_LENGTH];
308
	int maxw1=0, maxw2=0, maxw3=0, maxw4=0, maxw5=0, maxwv=0;
309
	int nfields, firstmapping, footer_gap, i, maxw_;
310
	char *ret, *map_basename, c, has_vmflags = 0;
311 312

	ret = fgets(mapbuf, sizeof mapbuf, f);
313
	firstmapping = 2;
314 315 316 317 318 319
	while (ret != NULL) {
		/* === READ MAPPING === */
		map_desc[0] = '\0';
		nfields = sscanf(mapbuf,
				 "%"NUML"[0-9a-f]-%"NUML"[0-9a-f] "
				 "%"DETL"s %"NUML"[0-9a-f] "
320
				 "%63[0-9a-f:] %"NUML"s %127[^\n]",
321
				 start, end, perms, offset,
322
				 dev, inode, map_desc);
323 324 325 326
		/* Must read at least up to inode, else something has changed! */
		if (nfields < 6)
			xerrx(EXIT_FAILURE, _("Unknown format in smaps file!"));
		/* If line too long we dump everything else. */
327
		c = mapbuf[strlen(mapbuf) - 1];
328 329 330 331
		while (c != '\n') {
			ret = fgets(mapbuf, sizeof mapbuf, f);
			c = mapbuf[strlen(mapbuf) - 1];
		}
332

333
		/* Store maximum widths for printing nice later */
334
		if (strlen(start ) > maxw1)	maxw1 = strlen(start);
335
		if (strlen(perms ) > maxw2)	maxw2 = strlen(perms);
336 337 338
		if (strlen(offset) > maxw3)	maxw3 = strlen(offset);
		if (strlen(dev   ) > maxw4)	maxw4 = strlen(dev);
		if (strlen(inode ) > maxw5)	maxw5 = strlen(inode);
339 340 341 342 343 344 345 346

		ret = fgets(mapbuf, sizeof mapbuf, f);
		nfields = sscanf(mapbuf, "%"DETL"[^:]: %"NUML"[0-9] kB %c",
				 detail_desc, value_str, &c);
		listnode = listhead;
		/* === READ MAPPING DETAILS === */
		while (ret != NULL && nfields == 2) {

347 348
			if (!is_enabled(detail_desc)) goto loop_end;

349 350
			/* === CREATE LIST AND FILL description FIELD === */
			if (listnode == NULL) {
351
				assert(firstmapping == 2);
352 353 354 355 356 357 358 359 360 361
				listnode = calloc(1, sizeof *listnode);
				if (listhead == NULL) {
					assert(listtail == NULL);
					listhead = listnode;
				} else {
					listtail->next = listnode;
				}
				listtail = listnode;
				/* listnode was calloc()ed so all fields are already NULL! */
				strcpy(listnode->description, detail_desc);
362 363
				if (!q_option) listnode->max_width = strlen(detail_desc);
				else listnode->max_width = 0;
364 365
			} else {
			/* === LIST EXISTS  === */
366
				if (strcmp(listnode->description, detail_desc) != 0)
367 368 369 370 371 372
					xerrx(EXIT_FAILURE, "ERROR: %s %s",
					      _("inconsistent detail field in smaps file, line:\n"),
					      mapbuf);
			}
			strcpy(listnode->value_str, value_str);
			sscanf(value_str, "%"KLF"u", &listnode->value);
373 374
			if (firstmapping == 2) {
				listnode->total += listnode->value;
375 376 377 378 379
				if (q_option) {
					maxw_ = strlen(listnode->value_str);
					if (maxw_ > listnode->max_width)
						listnode->max_width = maxw_;
				}
380
			}
381 382 383 384 385 386
			listnode = listnode->next;
loop_end:
			ret = fgets(mapbuf, sizeof mapbuf, f);
			nfields = sscanf(mapbuf, "%"DETL"[^:]: %"NUML"[0-9] kB %c",
					 detail_desc, value_str, &c);
		}
387 388 389 390 391 392 393 394 395

		/* === GET VMFLAGS === */
		nfields = sscanf(mapbuf, "VmFlags: %[a-z ]", vmflags);
		if (nfields == 1) {
			if (! has_vmflags) has_vmflags = 1;
			ret = fgets(mapbuf, sizeof mapbuf, f);
			if (strlen(vmflags) > maxwv) maxwv = strlen(vmflags);
		}

396 397 398 399 400
		if (firstmapping == 2) { /* width measurement stage, do not print anything yet */
			if (ret == NULL) {	/* once the end of file is reached ...*/
				firstmapping = 1;  /* ... we reset the file position to the beginning of the file */
				fseek(f, 0, SEEK_SET);  /* ... and repeat the process with printing enabled */
				ret = fgets(mapbuf, sizeof mapbuf, f); /* this is not ideal and needs to be redesigned one day */
401

402 403 404 405 406 407 408
				if (!q_option) {
					/* calculate width of totals */
					for (listnode=listhead; listnode!=NULL; listnode=listnode->next) {
						maxw_ = integer_width(listnode->total);
						if (maxw_ > listnode->max_width)
							listnode->max_width = maxw_;
					}
409 410
				}

411 412 413
			}
		} else {		 /* the maximum widths have been measured, we've already reached the printing stage */
			/* === PRINT THIS MAPPING === */
414

415 416
			/* Print header */
			if (firstmapping && !q_option) {
417

418
				maxw1 = justify_print(nls_Address, maxw1, 1);
419

420 421
				if (is_enabled(nls_Perm))
					maxw2 = justify_print(nls_Perm, maxw2, 1);
422

423 424
				if (is_enabled(nls_Offset))
					maxw3 = justify_print(nls_Offset, maxw3, 1);
425

426 427
				if (is_enabled(nls_Device))
					maxw4 = justify_print(nls_Device, maxw4, 1);
428

429 430
				if (is_enabled(nls_Inode))
					maxw5 = justify_print(nls_Inode, maxw5, 1);
431 432

				for (listnode=listhead; listnode!=NULL; listnode=listnode->next)
433
					justify_print(listnode->description, listnode->max_width, 1);
434

435 436 437
				if (has_vmflags && is_enabled("VmFlags"))
					printf(" %*s", maxwv, "VmFlags");

438 439 440 441
				if (is_enabled(nls_Mapping))
					justify_print(nls_Mapping, 0, 0);
				else
					printf("\n");
442
			}
443

444
			/* Print data */
445
			printf("%*s", maxw1, start);    /* Address field is always enabled */
446

447 448
			if (is_enabled(nls_Perm))
				printf(" %*s", maxw2, perms);
449

450
			if (is_enabled(nls_Offset))
451
				printf(" %*s", maxw3, offset);
452

453
			if (is_enabled(nls_Device))
454
				printf(" %*s", maxw4, dev);
455

456
			if (is_enabled(nls_Inode))
457
				printf(" %*s", maxw5, inode);
458

459 460
			for (listnode=listhead; listnode!=NULL; listnode=listnode->next)
				printf(" %*s", listnode->max_width, listnode->value_str);
461

462 463
			if (has_vmflags && is_enabled("VmFlags"))
				printf(" %*s", maxwv, vmflags);
464

465
			if (is_enabled(nls_Mapping)) {
466 467 468 469 470 471 472 473 474 475 476 477 478 479
				if (map_desc_showpath) {
					printf(" %s", map_desc);
				} else {
					map_basename = strrchr(map_desc, '/');
					if (!map_basename) {
						printf(" %s", map_desc);
					} else {
						printf(" %s", map_basename + 1);
					}

				}
			}

			printf("\n");
480

481
			firstmapping = 0;
482 483

		}
484 485
	}
	/* === PRINT TOTALS === */
486 487
	if (!q_option && listhead!=NULL) { /* footer enabled and non-empty */

488
		                            footer_gap  = maxw1 + 1; /* Address field is always enabled */
489
		if (is_enabled(nls_Perm  )) footer_gap += maxw2 + 1;
490 491 492
		if (is_enabled(nls_Offset)) footer_gap += maxw3 + 1;
		if (is_enabled(nls_Device)) footer_gap += maxw4 + 1;
		if (is_enabled(nls_Inode )) footer_gap += maxw5 + 1;
493 494 495 496

		for (i=0; i<footer_gap; i++) putc(' ', stdout);

		for (listnode=listhead; listnode!=NULL; listnode=listnode->next) {
497 498 499 500
			for (i=0; i<listnode->max_width; i++)
				putc('=', stdout);
			putc(' ', stdout);
		}
501

502
		putc('\n', stdout);
503 504 505

		for (i=0; i<footer_gap; i++) putc(' ', stdout);

506 507
		for (listnode=listhead; listnode!=NULL; listnode=listnode->next)
			printf("%*lu ", listnode->max_width, listnode->total);
508

509 510 511 512 513
		fputs("KB \n", stdout);
	}
	/* We don't free() the list, it's used for all PIDs passed as arguments */
}

514 515 516 517 518 519 520
static int one_proc(proc_t * p)
{
	char buf[32];
	FILE *fp;
	unsigned long total_shared = 0ul;
	unsigned long total_private_readonly = 0ul;
	unsigned long total_private_writeable = 0ul;
521
	unsigned KLONG diff = 0;
Mike Frysinger's avatar
Mike Frysinger committed
522
	const char *cp2 = NULL;
523 524 525 526 527 528
	unsigned long long rss = 0ull;
	unsigned long long private_dirty = 0ull;
	unsigned long long shared_dirty = 0ull;
	unsigned long long total_rss = 0ull;
	unsigned long long total_private_dirty = 0ull;
	unsigned long long total_shared_dirty = 0ull;
529
	int maxw1=0, maxw2=0, maxw3=0, maxw4=0, maxw5=0;
530 531 532 533 534 535

	/* Overkill, but who knows what is proper? The "w" prog uses
	 * the tty width to determine this.
	 */
	int maxcmd = 0xfffff;

536 537 538 539
	escape_command(cmdbuf, p, sizeof cmdbuf, &maxcmd,
		       ESC_ARGS | ESC_BRACKETS);
	printf("%u:   %s\n", p->tgid, cmdbuf);

540
	if (x_option || X_option || c_option) {
541
		sprintf(buf, "/proc/%u/smaps", p->tgid);
542 543 544 545 546
		if ((fp = fopen(buf, "r")) == NULL)
			return 1;
	} else {
		sprintf(buf, "/proc/%u/maps", p->tgid);
		if ((fp = fopen(buf, "r")) == NULL)
547 548 549
			return 1;
	}

550
	if (X_option || c_option) {
551 552 553 554
		print_extended_maps(fp);
		return 0;
	}

555 556 557 558 559 560 561 562 563 564 565 566
	if (x_option) {
		maxw1 = 16;
		if (sizeof(KLONG) == 4) maxw1 = 8;
		maxw2 = maxw3 = maxw4 = 7;
		maxw5 = 5;
		if (!q_option) {
			maxw1 = justify_print(nls_Address, maxw1, 0);
			maxw2 = justify_print(nls_Kbytes, maxw2, 1);
			maxw3 = justify_print(nls_RSS, maxw3, 1);
			maxw4 = justify_print(nls_Dirty, maxw4, 1);
			maxw5 = justify_print(nls_Mode, maxw5, 0);
			justify_print(nls_Mapping, 0, 0);
567
		}
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
	}

	if (d_option) {
		maxw1 = 16;
		if (sizeof(KLONG) == 4) maxw1 = 8;
		maxw2 = 7;
		maxw3 = 5;
		maxw4 = 16;
		maxw5 = 9;
		if (!q_option) {
			maxw1 = justify_print(nls_Address, maxw1, 0);
			maxw2 = justify_print(nls_Kbytes, maxw2, 1);
			maxw3 = justify_print(nls_Mode, maxw3, 0);
			maxw4 = justify_print(nls_Offset, maxw4, 0);
			maxw5 = justify_print(nls_Device, maxw5, 0);
			justify_print(nls_Mapping, 0, 0);
584 585 586 587
		}
	}

	while (fgets(mapbuf, sizeof mapbuf, fp)) {
588
		char perms[32];
589 590
		/* to clean up unprintables */
		char *tmp;
591
		unsigned KLONG start, end;
592 593 594
		unsigned long long file_offset, inode;
		unsigned dev_major, dev_minor;
		unsigned long long smap_value;
595
		char smap_key[21];
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618

		/* hex values are lower case or numeric, keys are upper */
		if (mapbuf[0] >= 'A' && mapbuf[0] <= 'Z') {
			/* Its a key */
			if (sscanf
			    (mapbuf, "%20[^:]: %llu", smap_key,
			     &smap_value) == 2) {
				if (strncmp("Rss", smap_key, 3) == 0) {
					rss = smap_value;
					total_rss += smap_value;
					continue;
				}
				if (strncmp("Shared_Dirty", smap_key, 12) == 0) {
					shared_dirty = smap_value;
					total_shared_dirty += smap_value;
					continue;
				}
				if (strncmp("Private_Dirty", smap_key, 13) == 0) {
					private_dirty = smap_value;
					total_private_dirty += smap_value;
					continue;
				}
				if (strncmp("Swap", smap_key, 4) == 0) {
619
					/*doesn't matter as long as last */
620 621 622 623 624
					printf("%0*" KLF "x %*lu %*llu %*llu %*s %s\n",
					       maxw1, start,
					       maxw2, (unsigned long)(diff >> 10),
					       maxw3, rss,
					       maxw4, (private_dirty + shared_dirty),
625
					       maxw5, perms,
626
					       cp2);
627
					/* reset some counters */
628 629
					rss = shared_dirty = private_dirty = 0ull;
					diff = 0;
630 631 632
					continue;
				}
			}
633 634
			/* Other keys or not a key-value pair */
			continue;
635
		}
636
		sscanf(mapbuf, "%" KLF "x-%" KLF "x %31s %llx %x:%x %llu", &start,
637
		       &end, perms, &file_offset, &dev_major, &dev_minor,
638 639
		       &inode);

640
		if (end - 1 < range_low)
641
			continue;
642 643
		if (range_high < start)
			break;
644 645 646 647 648 649 650 651 652 653 654 655

		tmp = strchr(mapbuf, '\n');
		if (tmp)
			*tmp = '\0';
		tmp = mapbuf;
		while (*tmp) {
			if (!isprint(*tmp))
				*tmp = '?';
			tmp++;
		}

		diff = end - start;
656
		if (perms[3] == 's')
657
			total_shared += diff;
658 659 660
		if (perms[3] == 'p') {
			perms[3] = '-';
			if (perms[1] == 'w')
661 662 663 664 665 666 667 668
				total_private_writeable += diff;
			else
				total_private_readonly += diff;
		}
		/* format used by Solaris 9 and procps-3.2.0+ an 'R'
		 * if swap not reserved (MAP_NORESERVE, SysV ISM
		 * shared mem, etc.)
		 */
669 670
		perms[4] = '-';
		perms[5] = '\0';
671 672 673

		if (x_option) {
			cp2 =
674
			    mapping_name(p, start, diff, mapbuf, map_desc_showpath, dev_major,
675 676 677 678 679 680
					 dev_minor, inode);
			/* printed with the keys */
			continue;
		}
		if (d_option) {
			const char *cp =
681
			    mapping_name(p, start, diff, mapbuf, map_desc_showpath, dev_major,
682
					 dev_minor, inode);
683 684 685
			printf("%0*" KLF "x %*lu %*s %0*llx %*.*s%03x:%05x %s\n",
			       maxw1, start,
			       maxw2, (unsigned long)(diff >> 10),
686
			       maxw3, perms,
687 688 689
			       maxw4, file_offset,
			       (maxw5-9), (maxw5-9), " ", dev_major, dev_minor,
			       cp);
690 691 692
		}
		if (!x_option && !d_option) {
			const char *cp =
693
			    mapping_name(p, start, diff, mapbuf, map_desc_showpath, dev_major,
694 695
					 dev_minor, inode);
			printf((sizeof(KLONG) == 8)
696 697
			       ? "%016" KLF "x %6luK %s %s\n"
			       : "%08lx %6luK %s %s\n",
698
			       start, (unsigned long)(diff >> 10), perms, cp);
699 700 701
		}

	}
702
	fclose(fp);
703 704
	if (!q_option) {
		if (x_option) {
705 706 707 708 709 710 711 712
			if (sizeof(KLONG) == 4)
				justify_print("--------", maxw1, 0);
			else
				justify_print("----------------", maxw1, 0);
			justify_print("-------", maxw2, 1);
			justify_print("-------", maxw3, 1);
			justify_print("-------", maxw4, 1);
			printf("\n");
713

714 715 716 717 718 719 720 721
			printf("%-*s ", maxw1, _("total kB"));
			printf("%*ld %*llu %*llu\n",
				maxw2, (total_shared +
					total_private_writeable +
					total_private_readonly) >> 10,
				maxw3, total_rss,
				maxw4, (total_shared_dirty +
					total_private_dirty));
722 723 724
		}
		if (d_option) {
			printf
Sami Kerola's avatar
Sami Kerola committed
725
			    (_("mapped: %ldK    writeable/private: %ldK    shared: %ldK\n"),
726 727 728 729 730 731
			     (total_shared + total_private_writeable +
			      total_private_readonly) >> 10,
			     total_private_writeable >> 10, total_shared >> 10);
		}
		if (!x_option && !d_option) {
			if (sizeof(KLONG) == 8)
732 733
				/* Translation Hint: keep total string length
				 * as 24 characters. Adjust %16 if needed*/
Sami Kerola's avatar
Sami Kerola committed
734
				printf(_(" total %16ldK\n"),
735 736 737
				       (total_shared + total_private_writeable +
					total_private_readonly) >> 10);
			else
738 739
				/* Translation Hint: keep total string length
				 * as 16 characters. Adjust %8 if needed*/
Sami Kerola's avatar
Sami Kerola committed
740
				printf(_(" total %8ldK\n"),
741 742 743 744 745 746
				       (total_shared + total_private_writeable +
					total_private_readonly) >> 10);
		}
	}

	return 0;
csmall's avatar
csmall committed
747 748
}

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
static void range_arguments(char *optarg)
{
	char *arg1;
	char *arg2;

	arg1 = xstrdup(optarg);
	arg2 = strchr(arg1, ',');
	if (arg2)
		*arg2 = '\0';
	if (arg2)
		++arg2;
	else
		arg2 = arg1;
	if (arg1 && *arg1)
		range_low = STRTOUKL(arg1, &arg1, 16);
	if (*arg2)
		range_high = STRTOUKL(arg2, &arg2, 16);
	if (arg1 && (*arg1 || *arg2))
		xerrx(EXIT_FAILURE, "%s: '%s'", _("failed to parse argument"),
		      optarg);
}

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791

#define MAX_CNF_LINE_LEN		1024

#define SECTION_ID_NONE			0
#define SECTION_ID_UNSUPPORTED		1

#define SECTION_STR_FIELDS_DISPLAY	"[Fields Display]"
#define SECTION_STR_FIELDS_DISPLAY_LEN	(sizeof(SECTION_STR_FIELDS_DISPLAY) - 1)
#define SECTION_ID_FIELDS_DISPLAY	2

#define SECTION_STR_MAPPING		"[Mapping]"
#define SECTION_STR_MAPPING_LEN		(sizeof(SECTION_STR_MAPPING) - 1)
#define SECTION_ID_MAPPING		3

static int config_read (char *rc_filename)
{
	FILE *f;
	char line_buf[MAX_CNF_LINE_LEN + 1];
	char tmp_buf [MAX_CNF_LINE_LEN + 1];
	char *trimmed;
	int length;
792
	char *tail, *token;
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
	int line_cnt, section_id;

	f = fopen(rc_filename, "r");

	if (!f) return 0; /* can't open the file for reading */

	line_cnt = 0;
	section_id = SECTION_ID_NONE;

	while (fgets (line_buf, MAX_CNF_LINE_LEN + 1, f)) {

		line_cnt++;

		/* get rid of the LF char */
		length = strlen(line_buf);
		if (length > 0 && line_buf[length - 1] == '\n') {
			line_buf[length - 1] = '\0';
		} else if (length == MAX_CNF_LINE_LEN) { /* no LF char -> line too long */
			xwarnx(_("config line too long - line %d"), line_cnt);
			/* ignoring the tail */
			while (fgets (tmp_buf, MAX_CNF_LINE_LEN + 1, f) &&
				(length = strlen(tmp_buf))>0 &&
				 tmp_buf[length - 1] != '\n') ;
		}

		/* trim leading whitespaces */
		trimmed = line_buf;
		while (*trimmed == ' ' || *trimmed == '\t') trimmed++;

		/* skip comments and empty lines */
		if (*trimmed == '#' || *trimmed == '\0') continue;

		if (*trimmed == '[') { /* section */
			if        (!strncmp(trimmed, SECTION_STR_FIELDS_DISPLAY, SECTION_STR_FIELDS_DISPLAY_LEN)) {
				trimmed += SECTION_STR_FIELDS_DISPLAY_LEN;
				section_id = SECTION_ID_FIELDS_DISPLAY;
			} else if (!strncmp(trimmed, SECTION_STR_MAPPING, SECTION_STR_MAPPING_LEN)) {
				trimmed += SECTION_STR_MAPPING_LEN;
				section_id = SECTION_ID_MAPPING;
			} else {
				while (*trimmed != ']' || *trimmed == '\0') trimmed++;
				if (*trimmed == ']') {
					section_id = SECTION_ID_UNSUPPORTED;
					xwarnx(_("unsupported section found in the config - line %d"), line_cnt);
					trimmed++;
				} else {
					xwarnx(_("syntax error found in the config - line %d"), line_cnt);
				}
			}

			/* trim trailing whitespaces */
			while (*trimmed == ' ' || *trimmed == '\t') trimmed++;

			/* skip comments and empty tails */
			if (*trimmed == '#' || *trimmed == '\0') continue;

			/* anything else found on the section line ??? */
			xwarnx(_("syntax error found in the config - line %d"), line_cnt);
		}

		switch (section_id) {
			case SECTION_ID_FIELDS_DISPLAY:
				token = strtok (trimmed, " \t");

				if (token) {
					tail = strtok (NULL, " \t");

					if (tail && *tail != '#') {
						xwarnx(_("syntax error found in the config - line %d"), line_cnt);
					}

					/* add the field in the list */
					cnf_listnode = calloc(1, sizeof *cnf_listnode);
					snprintf(cnf_listnode -> description, sizeof(cnf_listnode -> description), "%s", token);
					cnf_listnode -> next = cnf_listhead;
					cnf_listhead = cnf_listnode;
				}

				break;

			case SECTION_ID_MAPPING:
				token = strtok (trimmed, " \t");

				if (token) {
					tail = strtok (NULL, " \t");

					if (tail && *tail != '#') {
						xwarnx(_("syntax error found in the config - line %d"), line_cnt);
					}

					if (!strcmp(token,"ShowPath")) map_desc_showpath = !map_desc_showpath;
				}

				break;

			case SECTION_ID_UNSUPPORTED:
				break; /* ignore the content */

			default:
				xwarnx(_("syntax error found in the config - line %d"), line_cnt);
		}
        }

	fclose(f);

	return 1;
}


static int config_create (char *rc_filename)
{
	FILE *f;

	/* check if rc exists */
	f = fopen(rc_filename, "r");

	if (f) {  /* file exists ... let user to delete/remove it first */
		fclose(f);
		xwarnx(_("the file already exists - delete or rename it first"));
		return 0;
	}

	/* file doesn't exist */

	f = fopen(rc_filename, "w");

	if (!f) return 0; /* can't open the file for writing */

	/* current rc template, might change in the future */
	fprintf(f,"# pmap's Config File\n");
	fprintf(f,"\n");
	fprintf(f,"# All the entries are case sensitive.\n");
	fprintf(f,"# Unsupported entries are ignored!\n");
	fprintf(f,"\n");
	fprintf(f,"[Fields Display]\n");
	fprintf(f,"\n");
	fprintf(f,"# To enable a field uncomment its entry\n");
	fprintf(f,"\n");
931
	fprintf(f,"#%s\n", nls_Perm);
932 933 934
	fprintf(f,"#%s\n", nls_Offset);
	fprintf(f,"#%s\n", nls_Device);
	fprintf(f,"#%s\n", nls_Inode);
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
	fprintf(f,"#Size\n");
	fprintf(f,"#Rss\n");
	fprintf(f,"#Pss\n");
	fprintf(f,"#Shared_Clean\n");
	fprintf(f,"#Shared_Dirty\n");
	fprintf(f,"#Private_Clean\n");
	fprintf(f,"#Private_Dirty\n");
	fprintf(f,"#Referenced\n");
	fprintf(f,"#Anonymous\n");
	fprintf(f,"#AnonHugePages\n");
	fprintf(f,"#Swap\n");
	fprintf(f,"#KernelPageSize\n");
	fprintf(f,"#MMUPageSize\n");
	fprintf(f,"#Locked\n");
	fprintf(f,"#VmFlags\n");
950
	fprintf(f,"#%s\n", nls_Mapping);
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
	fprintf(f,"\n");
	fprintf(f,"\n");
	fprintf(f,"[Mapping]\n");
	fprintf(f,"\n");
	fprintf(f,"# to show paths in the mapping column uncomment the following line\n");
	fprintf(f,"#ShowPath\n");
	fprintf(f,"\n");

	fclose(f);

	return 1;
}


/* returns rc filename based on the program_invocation_short_name */
static char *get_default_rc_filename(void)
{
	char *rc_filename;
969
	int rc_filename_len;
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
	const char *homedir;

	homedir = getenv("HOME");
	if (!homedir) {
		xwarnx(_("HOME variable undefined"));
		return NULL;
	}

	rc_filename_len = snprintf(NULL, 0, "%s/.%src", homedir, program_invocation_short_name);

	rc_filename = (char *) calloc (1, rc_filename_len + 1);
	if (!rc_filename) {
		xwarnx(_("memory allocation failed"));
		return NULL;
	}

	snprintf(rc_filename, rc_filename_len + 1, "%s/.%src", homedir, program_invocation_short_name);

	return rc_filename;
}


992 993
int main(int argc, char **argv)
{
994
	pid_t *pidlist;
995 996 997
	unsigned count = 0;
	PROCTAB *PT;
	proc_t p;
998
	int ret = 0, c, conf_ret;
999
	char *rc_filename = NULL;
1000 1001 1002 1003 1004 1005 1006 1007

	static const struct option longopts[] = {
		{"extended", no_argument, NULL, 'x'},
		{"device", no_argument, NULL, 'd'},
		{"quiet", no_argument, NULL, 'q'},
		{"range", required_argument, NULL, 'A'},
		{"help", no_argument, NULL, 'h'},
		{"version", no_argument, NULL, 'V'},
1008 1009 1010 1011 1012
		{"read-rc", no_argument, NULL, 'c'},
		{"read-rc-from", required_argument, NULL, 'C'},
		{"create-rc", no_argument, NULL, 'n'},
		{"create-rc-to", required_argument, NULL, 'N'},
		{"show-path", no_argument, NULL, 'p'},
1013 1014 1015
		{NULL, 0, NULL, 0}
	};

1016
#ifdef HAVE_PROGRAM_INVOCATION_NAME
1017
	program_invocation_name = program_invocation_short_name;
1018
#endif
1019
	nls_initialize();
1020
	atexit(close_stdout);
1021

1022 1023 1024
	if (argc < 2)
		usage(stderr);

1025
	while ((c = getopt_long(argc, argv, "xXrdqA:hVcC:nN:p", longopts, NULL)) != -1)
1026 1027 1028 1029
		switch (c) {
		case 'x':
			x_option = 1;
			break;
1030 1031 1032
		case 'X':
			X_option++;
			break;
1033
		case 'r':
1034
			xwarnx(_("option -r is ignored as SunOS compatibility"));
1035 1036 1037 1038 1039 1040 1041 1042
			break;
		case 'd':
			d_option = 1;
			break;
		case 'q':
			q_option = 1;
			break;
		case 'A':
1043
			range_arguments(optarg);
1044 1045 1046 1047
			break;
		case 'h':
			usage(stdout);
		case 'V':
Sami Kerola's avatar
Sami Kerola committed
1048
			printf(PROCPS_NG_VERSION);
1049
			return EXIT_SUCCESS;
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
		case 'c':
			c_option = 1;
			break;
		case 'C':
			C_option = 1;
			rc_filename = optarg;
			break;
		case 'n':
			n_option = 1;
			break;
		case 'N':
			N_option = 1;
			rc_filename = optarg;
			break;
		case 'p':
			map_desc_showpath = 1;
			break;
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
		case 'a':	/* Sun prints anon/swap reservations */
		case 'F':	/* Sun forces hostile ptrace-like grab */
		case 'l':	/* Sun shows unresolved dynamic names */
		case 'L':	/* Sun shows lgroup info */
		case 's':	/* Sun shows page sizes */
		case 'S':	/* Sun shows swap reservations */
		default:
			usage(stderr);
		}

	argc -= optind;
	argv += optind;

1080 1081 1082
	if (c_option + C_option + d_option + n_option + N_option + x_option + !!X_option > 1)
		xerrx(EXIT_FAILURE, _("options -c, -C, -d, -n, -N, -x, -X are mutually exclusive"));

1083
	if ((n_option || N_option) && (q_option || map_desc_showpath))
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
		xerrx(EXIT_FAILURE, _("options -p, -q are mutually exclusive with -n, -N"));

	if ((n_option || N_option) && argc > 0)
		xerrx(EXIT_FAILURE, _("too many arguments"));

	if (N_option) {
		if (config_create(rc_filename)) {
			xwarnx(_("rc file successfully created, feel free to edit the content"));
			return (EXIT_SUCCESS);
		} else {
			xerrx(EXIT_FAILURE, _("couldn't create the rc file"));
		}
	}

	if (n_option) {
		rc_filename = get_default_rc_filename();

		if (!rc_filename) return(EXIT_FAILURE);

		conf_ret = config_create(rc_filename); free(rc_filename);

		if (conf_ret) {
			xwarnx(_("~/.%src file successfully created, feel free to edit the content"), program_invocation_short_name);
			return (EXIT_SUCCESS);
		} else {
			xerrx(EXIT_FAILURE, _("couldn't create ~/.%src"), program_invocation_short_name);
		}
	}

1113
	if (argc < 1)
1114
		xerrx(EXIT_FAILURE, _("argument missing"));
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136

	if (C_option) c_option = 1;

	if (c_option) {

		if (!C_option) rc_filename = get_default_rc_filename();

		if (!rc_filename) return(EXIT_FAILURE);

		conf_ret = config_read(rc_filename);

		if (!conf_ret) {
			if (C_option) {
				xerrx(EXIT_FAILURE, _("couldn't read the rc file"));
			} else {
				xwarnx(_("couldn't read ~/.%src"), program_invocation_short_name);
				free(rc_filename);
				return(EXIT_FAILURE);
			}
		}

	}
1137

1138
	pidlist = xmalloc(sizeof(pid_t) * (argc+1));
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

	while (*argv) {
		char *walk = *argv++;
		char *endp;
		unsigned long pid;
		if (!strncmp("/proc/", walk, 6)) {
			walk += 6;
			/*  user allowed to do: pmap /proc/PID */
			if (*walk < '0' || *walk > '9')
				continue;
		}
		if (*walk < '0' || *walk > '9')
			usage(stderr);
		pid = strtoul(walk, &endp, 0);
		if (pid < 1ul || pid > 0x7ffffffful || *endp)
			usage(stderr);
		pidlist[count++] = pid;
	}

	discover_shm_minor();

	memset(&p, '\0', sizeof(p));
	/* old libproc interface is zero-terminated */
	pidlist[count] = 0;
	PT = openproc(PROC_FILLSTAT | PROC_FILLARG | PROC_PID, pidlist);
	while (readproc(PT, &p)) {
		ret |= one_proc(&p);
		count--;
	}
	closeproc(PT);
Sami Kerola's avatar
Sami Kerola committed
1169
	free(pidlist);
1170

1171
	/* cleaning the list used for the -c/-X/-XX modes */
1172 1173 1174 1175 1176 1177
	for (listnode = listhead; listnode != NULL ; ) {
		listnode = listnode -> next;
		free(listhead);
		listhead = listnode;
	}

1178 1179 1180 1181 1182 1183 1184
	/* cleaning the list used for the -c mode */
	for (cnf_listnode = cnf_listhead; cnf_listnode != NULL ; ) {
		cnf_listnode = cnf_listnode -> next;
		free(cnf_listhead);
		cnf_listhead = cnf_listnode;
	}

1185 1186 1187 1188
	if (count)
		/* didn't find all processes asked for */
		ret |= 42;
	return ret;
csmall's avatar
csmall committed
1189
}