2 * lslocks(8) - list local system locks
4 * Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
6 * Very generally based on lslk(8) by Victor A. Abell <abe@purdue.edu>
7 * Since it stopped being maintained over a decade ago, this
8 * program should be considered its replacement.
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it would be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 #include <sys/types.h>
38 #include <libsmartcols.h>
40 #include "pathnames.h"
41 #include "canonicalize.h"
47 #include "closestream.h"
50 #include "column-list-table.h"
51 #include "fileutils.h"
72 const char * const name
; /* header */
73 double whint
; /* width hint (N < 1 is in percent of termwidth) */
74 int flags
; /* SCOLS_FL_* */
78 /* columns descriptions */
79 static struct colinfo infos
[] = {
80 [COL_SRC
] = { "COMMAND",15, 0, N_("command of the process holding the lock") },
81 [COL_PID
] = { "PID", 5, SCOLS_FL_RIGHT
, N_("PID of the process holding the lock") },
82 [COL_TYPE
] = { "TYPE", 5, SCOLS_FL_RIGHT
, N_("kind of lock") },
83 [COL_SIZE
] = { "SIZE", 4, SCOLS_FL_RIGHT
, N_("size of the lock, use <number> if --bytes is given") },
84 [COL_INODE
] = { "INODE", 5, SCOLS_FL_RIGHT
, N_("inode number") },
85 [COL_MAJMIN
] = { "MAJ:MIN", 6, 0, N_("major:minor device number") },
86 [COL_MODE
] = { "MODE", 5, 0, N_("lock access mode") },
87 [COL_M
] = { "M", 1, 0, N_("mandatory state of the lock: 0 (none), 1 (set)")},
88 [COL_START
] = { "START", 10, SCOLS_FL_RIGHT
, N_("relative byte offset of the lock")},
89 [COL_END
] = { "END", 10, SCOLS_FL_RIGHT
, N_("ending offset of the lock")},
90 [COL_PATH
] = { "PATH", 0, SCOLS_FL_TRUNC
, N_("path of the locked file")},
91 [COL_BLOCKER
] = { "BLOCKER", 0, SCOLS_FL_RIGHT
, N_("PID of the process blocking the lock") },
92 [COL_HOLDERS
] = { "HOLDERS", 0, SCOLS_FL_WRAP
, N_("HOLDERS of the lock") },
95 static int columns
[ARRAY_SIZE(infos
) * 2];
96 static size_t ncolumns
;
98 static struct libmnt_table
*tab
; /* /proc/self/mountinfo */
100 /* basic output flags */
101 static int no_headings
;
102 static int no_inaccessible
;
108 struct list_head locks
;
119 unsigned int mandatory
:1,
130 struct list_head chain
;
133 static int lock_tnode_compare(const void *a
, const void *b
)
135 struct lock_tnode
*anode
= ((struct lock_tnode
*)a
);
136 struct lock_tnode
*bnode
= ((struct lock_tnode
*)b
);
138 if (anode
->dev
> bnode
->dev
)
140 else if (anode
->dev
< bnode
->dev
)
143 if (anode
->inode
> bnode
->inode
)
145 else if (anode
->inode
< bnode
->inode
)
151 static void add_to_tree(void *troot
, struct lock
*l
)
153 struct lock_tnode tmp
= { .dev
= l
->dev
, .inode
= l
->inode
, };
154 struct lock_tnode
**head
= tfind(&tmp
, troot
, lock_tnode_compare
);
155 struct lock_tnode
*new_head
;
158 list_add_tail(&l
->locks
, &(*head
)->chain
);
162 new_head
= xmalloc(sizeof(*new_head
));
163 new_head
->dev
= l
->dev
;
164 new_head
->inode
= l
->inode
;
165 INIT_LIST_HEAD(&new_head
->chain
);
166 if (tsearch(new_head
, troot
, lock_tnode_compare
) == NULL
)
167 errx(EXIT_FAILURE
, _("failed to allocate memory"));
169 list_add_tail(&l
->locks
, &new_head
->chain
);
172 static void rem_lock(struct lock
*lock
)
181 list_del(&lock
->locks
);
185 static void disable_columns_truncate(void)
189 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++)
190 infos
[i
].flags
&= ~SCOLS_FL_TRUNC
;
194 * Associate the device's mountpoint for a filename
196 static char *get_fallback_filename(dev_t dev
)
198 struct libmnt_fs
*fs
;
202 tab
= mnt_new_table_from_file(_PATH_PROC_MOUNTINFO
);
207 fs
= mnt_table_find_devno(tab
, dev
, MNT_ITER_BACKWARD
);
211 xasprintf(&res
, "%s...", mnt_fs_get_target(fs
));
216 * Return the absolute path of a file from
217 * a given inode number (and its size)
219 static char *get_filename_sz(ino_t inode
, pid_t lock_pid
, size_t *size
)
226 char path
[PATH_MAX
] = { 0 },
227 sym
[PATH_MAX
] = { 0 }, *ret
= NULL
;
232 /* pid could be -1 for OFD locks */
236 * We know the pid so we don't have to
237 * iterate the *entire* filesystem searching
240 snprintf(path
, sizeof(path
), "/proc/%d/fd/", lock_pid
);
241 if (!(dirp
= opendir(path
)))
244 if ((sz
= strlen(path
)) >= (sizeof(path
) - 2))
247 if ((fd
= dirfd(dirp
)) < 0 )
250 while ((dp
= xreaddir(dirp
))) {
255 /* care only for numerical descriptors */
256 if (!strtol(dp
->d_name
, (char **) NULL
, 10) || errno
)
259 if (!fstatat(fd
, dp
->d_name
, &sb
, 0)
260 && inode
!= sb
.st_ino
)
263 if ((len
= readlinkat(fd
, dp
->d_name
, sym
, sizeof(sym
) - 1)) < 1)
278 * Return the inode number from a string
280 static ino_t
get_dev_inode(char *str
, dev_t
*dev
)
282 unsigned int maj
= 0, min
= 0;
285 if (sscanf(str
, "%x:%x:%ju", &maj
, &min
, &inum
) != 3)
286 errx(EXIT_FAILURE
, _("failed to parse '%s'"), str
);
288 *dev
= (dev_t
) makedev(maj
, min
);
292 struct override_info
{
297 static bool is_holder(struct lock
*l
, struct lock
*m
)
299 return (l
->start
== m
->start
&&
301 l
->inode
== m
->inode
&&
303 l
->mandatory
== m
->mandatory
&&
304 l
->blocked
== m
->blocked
&&
305 strcmp(l
->type
, m
->type
) == 0 &&
306 strcmp(l
->mode
, m
->mode
) == 0);
309 static void patch_lock(struct lock
*l
, void *fallback
)
311 struct lock_tnode tmp
= { .dev
= l
->dev
, .inode
= l
->inode
, };
312 struct lock_tnode
**head
= tfind(&tmp
, fallback
, lock_tnode_compare
);
318 list_for_each(p
, &(*head
)->chain
) {
319 struct lock
*m
= list_entry(p
, struct lock
, locks
);
320 if (is_holder(l
, m
)) {
321 /* size and id can be ignored. */
323 l
->cmdname
= xstrdup(m
->cmdname
);
329 static void add_to_list(void *locks
, struct lock
*l
)
331 list_add(&l
->locks
, locks
);
334 static struct lock
*get_lock(char *buf
, struct override_info
*oinfo
, void *fallback
)
339 struct lock
*l
= xcalloc(1, sizeof(*l
));
340 INIT_LIST_HEAD(&l
->locks
);
343 bool cmdname_unknown
= false;
345 for (tok
= strtok(buf
, " "), i
= 0; tok
;
346 tok
= strtok(NULL
, " "), i
++) {
349 * /proc/locks has *exactly* 8 "blocks" of text
350 * separated by ' ' - check <kernel>/fs/locks.c
357 tok
[strlen(tok
) - 1] = '\0';
358 l
->id
= strtos32_or_err(tok
, _("failed to parse ID"));
361 case 1: /* posix, flock, etc */
362 if (strcmp(tok
, "->") == 0) { /* optional field */
366 l
->type
= xstrdup(tok
);
369 case 2: /* is this a mandatory lock? other values are advisory or noinode */
370 l
->mandatory
= *tok
== 'M' ? 1 : 0;
372 case 3: /* lock mode */
373 l
->mode
= xstrdup(tok
);
378 * If user passed a pid we filter it later when adding
379 * to the list, no need to worry now. OFD locks use -1 PID.
383 l
->cmdname
= xstrdup(oinfo
->cmdname
);
385 l
->pid
= strtos32_or_err(tok
, _("failed to parse pid"));
387 l
->cmdname
= pid_get_cmdname(l
->pid
);
390 cmdname_unknown
= true;
397 case 5: /* device major:minor and inode number */
398 l
->inode
= get_dev_inode(tok
, &l
->dev
);
402 l
->start
= !strcmp(tok
, "EOF") ? 0 :
403 strtou64_or_err(tok
, _("failed to parse start"));
407 /* replace '\n' character */
408 tok
[strlen(tok
)-1] = '\0';
409 l
->end
= !strcmp(tok
, "EOF") ? 0 :
410 strtou64_or_err(tok
, _("failed to parse end"));
417 if ((!l
->blocked
) && fallback
&& !l
->cmdname
)
418 patch_lock(l
, fallback
);
421 l
->cmdname
= xstrdup(_("(unknown)"));
423 l
->cmdname
= xstrdup(_("(undefined)"));
425 l
->path
= get_filename_sz(l
->inode
, l
->pid
, &sz
);
427 /* no permissions -- ignore */
428 if (!l
->path
&& no_inaccessible
) {
434 /* probably no permission to peek into l->pid's path */
435 l
->path
= get_fallback_filename(l
->dev
);
443 static int get_pid_lock(void *locks
, void (*add_lock
)(void *, struct lock
*), FILE *fp
,
444 pid_t pid
, const char *cmdname
, int fd
)
447 struct override_info oinfo
= {
452 while (fgets(buf
, sizeof(buf
), fp
)) {
454 if (strncmp(buf
, "lock:\t", 6))
456 l
= get_lock(buf
+ 6, &oinfo
, NULL
);
462 Multiple recode locks can be taken via one fd. */
468 static int get_pid_locks(void *locks
, void (*add_lock
)(void *, struct lock
*), struct path_cxt
*pc
,
469 pid_t pid
, const char *cmdname
)
472 struct dirent
*d
= NULL
;
475 while (ul_path_next_dirent(pc
, &sub
, "fdinfo", &d
) == 0) {
479 if (ul_strtou64(d
->d_name
, &num
, 10) != 0) /* only numbers */
482 fdinfo
= ul_path_fopenf(pc
, "r", "fdinfo/%ju", num
);
486 get_pid_lock(locks
, add_lock
, fdinfo
, pid
, cmdname
, (int)num
);
493 static void get_pids_locks(void *locks
, void (*add_lock
)(void *, struct lock
*))
497 struct path_cxt
*pc
= NULL
;
499 pc
= ul_new_path(NULL
);
501 err(EXIT_FAILURE
, _("failed to alloc procfs handler"));
503 dir
= opendir(_PATH_PROC
);
505 err(EXIT_FAILURE
, _("failed to open /proc"));
507 while ((d
= readdir(dir
))) {
510 const char *cmdname
= NULL
;
512 if (procfs_dirent_get_pid(d
, &pid
) != 0)
515 if (procfs_process_init_path(pc
, pid
) != 0)
518 if (procfs_process_get_cmdname(pc
, buf
, sizeof(buf
)) <= 0)
522 get_pid_locks(locks
, add_lock
, pc
, pid
, cmdname
);
531 static int get_proc_locks(void *locks
, void (*add_lock
)(void *, struct lock
*), void *fallback
)
536 if (!(fp
= fopen(_PATH_PROC_LOCKS
, "r")))
539 while (fgets(buf
, sizeof(buf
), fp
)) {
540 struct lock
*l
= get_lock(buf
, NULL
, fallback
);
549 static int column_name_to_id(const char *name
, size_t namesz
)
555 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++) {
556 const char *cn
= infos
[i
].name
;
558 if (!strncasecmp(name
, cn
, namesz
) && !*(cn
+ namesz
))
561 warnx(_("unknown column: %s"), name
);
565 static inline int get_column_id(int num
)
568 assert((size_t) num
< ncolumns
);
569 assert(columns
[num
] < (int) ARRAY_SIZE(infos
));
575 static inline const struct colinfo
*get_column_info(unsigned num
)
577 return &infos
[ get_column_id(num
) ];
580 static pid_t
get_blocker(int id
, struct list_head
*locks
)
584 list_for_each(p
, locks
) {
585 struct lock
*l
= list_entry(p
, struct lock
, locks
);
587 if (l
->id
== id
&& !l
->blocked
)
594 static void xstrcoholder(char **str
, struct lock
*l
)
596 xstrfappend(str
, "%d,%s,%d",
597 l
->pid
, l
->cmdname
, l
->fd
);
600 static void add_scols_line(struct libscols_table
*table
, struct lock
*l
, struct list_head
*locks
, void *pid_locks
)
603 struct libscols_line
*line
;
605 * Whenever cmdname or filename is NULL it is most
606 * likely because there's no read permissions
607 * for the specified process.
609 const char *notfnd
= "";
614 line
= scols_table_new_line(table
, NULL
);
616 err(EXIT_FAILURE
, _("failed to allocate output line"));
618 for (i
= 0; i
< ncolumns
; i
++) {
621 switch (get_column_id(i
)) {
623 xasprintf(&str
, "%s", l
->cmdname
? l
->cmdname
: notfnd
);
626 xasprintf(&str
, "%d", l
->pid
);
629 xasprintf(&str
, "%s", l
->type
);
632 xasprintf(&str
, "%ju", (uintmax_t) l
->inode
);
636 xasprintf(&str
, "%u:%u", major(l
->dev
), minor(l
->dev
));
638 xasprintf(&str
, "%3u:%-3u", major(l
->dev
), minor(l
->dev
));
644 xasprintf(&str
, "%ju", l
->size
);
646 str
= size_to_human_string(SIZE_SUFFIX_1LETTER
, l
->size
);
649 xasprintf(&str
, "%s%s", l
->mode
, l
->blocked
? "*" : "");
652 xasprintf(&str
, "%d", l
->mandatory
? 1 : 0);
655 xasprintf(&str
, "%jd", l
->start
);
658 xasprintf(&str
, "%jd", l
->end
);
661 xasprintf(&str
, "%s", l
->path
? l
->path
: notfnd
);
665 pid_t bl
= l
->blocked
&& l
->id
?
666 get_blocker(l
->id
, locks
) : 0;
668 xasprintf(&str
, "%d", (int) bl
);
673 struct lock_tnode tmp
= { .dev
= l
->dev
, .inode
= l
->inode
, };
674 struct lock_tnode
**head
= tfind(&tmp
, pid_locks
, lock_tnode_compare
);
680 list_for_each(p
, &(*head
)->chain
) {
681 struct lock
*m
= list_entry(p
, struct lock
, locks
);
683 if (!is_holder(l
, m
))
687 xstrputc(&str
, '\n');
688 xstrcoholder(&str
, m
);
696 if (str
&& scols_line_refer_data(line
, i
, str
))
697 err(EXIT_FAILURE
, _("failed to add output data"));
701 static void rem_locks(struct list_head
*locks
)
703 struct list_head
*p
, *pnext
;
705 /* destroy the list */
706 list_for_each_safe(p
, pnext
, locks
) {
707 struct lock
*l
= list_entry(p
, struct lock
, locks
);
712 static void rem_tnode(void *node
)
714 struct lock_tnode
*tnode
= node
;
716 rem_locks(&tnode
->chain
);
720 static int get_json_type_for_column(int column_id
, int representing_in_bytes
)
724 if (!representing_in_bytes
)
725 return SCOLS_JSON_STRING
;
732 return SCOLS_JSON_NUMBER
;
734 return SCOLS_JSON_BOOLEAN
;
736 return SCOLS_JSON_ARRAY_STRING
;
738 return SCOLS_JSON_STRING
;
742 static int show_locks(struct list_head
*locks
, pid_t target_pid
, void *pid_locks
)
747 struct libscols_table
*table
;
749 table
= scols_new_table();
751 err(EXIT_FAILURE
, _("failed to allocate output table"));
753 scols_table_enable_raw(table
, raw
);
754 scols_table_enable_json(table
, json
);
755 scols_table_enable_noheadings(table
, no_headings
);
758 scols_table_set_name(table
, "locks");
760 for (i
= 0; i
< ncolumns
; i
++) {
761 struct libscols_column
*cl
;
762 const struct colinfo
*col
= get_column_info(i
);
764 cl
= scols_table_new_column(table
, col
->name
, col
->whint
, col
->flags
);
766 err(EXIT_FAILURE
, _("failed to allocate output column"));
768 if (col
->flags
& SCOLS_FL_WRAP
) {
769 scols_column_set_wrapfunc(cl
,
770 scols_wrapnl_chunksize
,
771 scols_wrapnl_nextchunk
,
773 scols_column_set_safechars(cl
, "\n");
777 int id
= get_column_id(i
);
778 int json_type
= get_json_type_for_column(id
, bytes
);
779 scols_column_set_json_type(cl
, json_type
);
784 /* prepare data for output */
785 list_for_each(p
, locks
) {
786 struct lock
*l
= list_entry(p
, struct lock
, locks
);
788 if (target_pid
&& target_pid
!= l
->pid
)
791 add_scols_line(table
, l
, locks
, pid_locks
);
794 scols_print_table(table
);
795 scols_unref_table(table
);
800 static void __attribute__((__noreturn__
)) usage(void)
804 fputs(USAGE_HEADER
, out
);
807 _(" %s [options]\n"), program_invocation_short_name
);
809 fputs(USAGE_SEPARATOR
, out
);
810 fputs(_("List local system locks.\n"), out
);
812 fputs(USAGE_OPTIONS
, out
);
813 fputs(_(" -b, --bytes print SIZE in bytes rather than in human readable format\n"), out
);
814 fputs(_(" -J, --json use JSON output format\n"), out
);
815 fputs(_(" -i, --noinaccessible ignore locks without read permissions\n"), out
);
816 fputs(_(" -n, --noheadings don't print headings\n"), out
);
817 fputs(_(" -o, --output <list> output columns (see --list-columns)\n"), out
);
818 fputs(_(" --output-all output all columns\n"), out
);
819 fputs(_(" -p, --pid <pid> display only locks held by this process\n"), out
);
820 fputs(_(" -r, --raw use the raw output format\n"), out
);
821 fputs(_(" -u, --notruncate don't truncate text in columns\n"), out
);
823 fputs(USAGE_SEPARATOR
, out
);
824 fputs(_(" -H, --list-columns list the available columns\n"), out
);
825 fprintf(out
, USAGE_HELP_OPTIONS(24));
826 fprintf(out
, USAGE_MAN_TAIL("lslocks(8)"));
831 static void __attribute__((__noreturn__
)) list_colunms(void)
833 struct libscols_table
*col_tb
= xcolumn_list_table_new(
834 "lslocks-columns", stdout
, raw
, json
);
836 for (size_t i
= 0; i
< ARRAY_SIZE(infos
); i
++) {
838 int json_type
= get_json_type_for_column(i
, bytes
);
839 xcolumn_list_table_append_line(col_tb
, infos
[i
].name
,
843 xcolumn_list_table_append_line(col_tb
, infos
[i
].name
,
844 -1, "<string|number>",
848 scols_print_table(col_tb
);
849 scols_unref_table(col_tb
);
854 int main(int argc
, char *argv
[])
856 int c
, rc
= 0, collist
= 0;
857 struct list_head proc_locks
;
858 void *pid_locks
= NULL
;
861 OPT_OUTPUT_ALL
= CHAR_MAX
+ 1
863 static const struct option long_opts
[] = {
864 { "bytes", no_argument
, NULL
, 'b' },
865 { "json", no_argument
, NULL
, 'J' },
866 { "pid", required_argument
, NULL
, 'p' },
867 { "help", no_argument
, NULL
, 'h' },
868 { "output", required_argument
, NULL
, 'o' },
869 { "output-all", no_argument
, NULL
, OPT_OUTPUT_ALL
},
870 { "notruncate", no_argument
, NULL
, 'u' },
871 { "version", no_argument
, NULL
, 'V' },
872 { "noheadings", no_argument
, NULL
, 'n' },
873 { "raw", no_argument
, NULL
, 'r' },
874 { "noinaccessible", no_argument
, NULL
, 'i' },
875 { "list-columns", no_argument
, NULL
, 'H' },
879 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
883 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
884 pid_t target_pid
= 0;
886 setlocale(LC_ALL
, "");
887 bindtextdomain(PACKAGE
, LOCALEDIR
);
889 close_stdout_atexit();
891 while ((c
= getopt_long(argc
, argv
,
892 "biJp:o:nruhVH", long_opts
, NULL
)) != -1) {
894 err_exclusive_options(c
, long_opts
, excl
, excl_st
);
907 target_pid
= strtos32_or_err(optarg
, _("invalid PID argument"));
913 for (ncolumns
= 0; ncolumns
< ARRAY_SIZE(infos
); ncolumns
++)
914 columns
[ncolumns
] = ncolumns
;
923 disable_columns_truncate();
930 print_version(EXIT_SUCCESS
);
934 errtryhelp(EXIT_FAILURE
);
939 list_colunms(); /* print end exit */
941 INIT_LIST_HEAD(&proc_locks
);
944 /* default columns */
945 columns
[ncolumns
++] = COL_SRC
;
946 columns
[ncolumns
++] = COL_PID
;
947 columns
[ncolumns
++] = COL_TYPE
;
948 columns
[ncolumns
++] = COL_SIZE
;
949 columns
[ncolumns
++] = COL_MODE
;
950 columns
[ncolumns
++] = COL_M
;
951 columns
[ncolumns
++] = COL_START
;
952 columns
[ncolumns
++] = COL_END
;
953 columns
[ncolumns
++] = COL_PATH
;
956 if (outarg
&& string_add_to_idarray(outarg
, columns
, ARRAY_SIZE(columns
),
957 &ncolumns
, column_name_to_id
) < 0)
962 /* get_pids_locks() get locks related information from "lock:" fields
963 * of /proc/$pid/fdinfo/$fd as fallback information.
964 * get_proc_locks() used the fallback information if /proc/locks
965 * doesn't provides enough information or provides staled information. */
966 get_pids_locks(&pid_locks
, add_to_tree
);
967 rc
= get_proc_locks(&proc_locks
, add_to_list
, &pid_locks
);
969 if (!rc
&& !list_empty(&proc_locks
))
970 rc
= show_locks(&proc_locks
, target_pid
, &pid_locks
);
972 tdestroy(pid_locks
, rem_tnode
);
973 rem_locks(&proc_locks
);
975 mnt_unref_table(tab
);