Fix: lttng: poptGetArg doesn't provide string ownership
[lttng-tools.git] / src / bin / lttng / commands / help.cpp
1 /*
2 * Copyright (C) 2015 Philippe Proulx <pproulx@efficios.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 */
7
8 #define _LGPL_SOURCE
9 #include <popt.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include "../command.hpp"
15 #include <common/utils.hpp>
16
17 #ifdef LTTNG_EMBED_HELP
18 static const char *help_msg =
19 #include <lttng-help.1.h>
20 ;
21 #endif
22
23 static const char *lttng_help_msg =
24 #ifdef LTTNG_EMBED_HELP
25 #include <lttng.1.h>
26 #else
27 NULL
28 #endif
29 ;
30
31 enum {
32 OPT_HELP = 1,
33 OPT_LIST_OPTIONS,
34 };
35
36 static struct poptOption long_options[] = {
37 /* longName, shortName, argInfo, argPtr, value, descrip, argDesc */
38 {"help", 'h', POPT_ARG_NONE, 0, OPT_HELP, 0, 0},
39 {"list-options", 0, POPT_ARG_NONE, NULL, OPT_LIST_OPTIONS, NULL, NULL},
40 {0, 0, 0, 0, 0, 0, 0}
41 };
42
43 /*
44 * cmd_help
45 */
46 int cmd_help(int argc, const char **argv, const struct cmd_struct commands[])
47 {
48 int opt, ret = CMD_SUCCESS;
49 const char *arg_cmd_name;
50 static poptContext pc;
51 const struct cmd_struct *cmd;
52 int found = 0;
53 const char *cmd_argv[2];
54
55 pc = poptGetContext(NULL, argc, argv, long_options, 0);
56 poptReadDefaultConfig(pc, 0);
57
58 while ((opt = poptGetNextOpt(pc)) != -1) {
59 switch (opt) {
60 case OPT_HELP:
61 SHOW_HELP();
62 goto end;
63 case OPT_LIST_OPTIONS:
64 list_cmd_options(stdout, long_options);
65 goto end;
66 default:
67 ret = CMD_UNDEFINED;
68 goto end;
69 }
70 }
71
72 /* Get command name */
73 arg_cmd_name = poptGetArg(pc);
74 if (arg_cmd_name == NULL) {
75 /* Fall back to lttng(1) */
76 ret = utils_show_help(1, "lttng", lttng_help_msg);
77 if (ret) {
78 ERR("Cannot show --help for `lttng`");
79 perror("exec");
80 ret = CMD_ERROR;
81 }
82
83 goto end;
84 }
85
86 /* Help about help? */
87 if (strcmp(arg_cmd_name, "help") == 0) {
88 SHOW_HELP();
89 goto end;
90 }
91
92 /* Make sure command name exists */
93 cmd = &commands[0];
94
95 while (cmd->name != NULL) {
96 if (strcmp(cmd->name, arg_cmd_name) == 0) {
97 found = 1;
98 break;
99 }
100
101 cmd++;
102 }
103
104 if (!found) {
105 ERR("Unknown command \"%s\"", arg_cmd_name);
106 ret = CMD_ERROR;
107 goto end;
108 }
109
110 /* Show command's help */
111 cmd_argv[0] = cmd->name;
112 cmd_argv[1] = "--help";
113 LTTNG_ASSERT(cmd->func);
114 ret = cmd->func(2, cmd_argv);
115
116 end:
117 poptFreeContext(pc);
118 return ret;
119 }
This page took 0.031803 seconds and 4 git commands to generate.