*/
void string_truncate_at_pattern(char *buf, const char *pattern);
+/**
+ * strdup_printf - allocate and write to buffer in printf format
+ * @fmt: printf-style format.
+ *
+ * Similar to the standard C sprintf() function but safer as it calculates the
+ * maximum space required and allocates memory to hold the output.
+ * The user must free the returned string.
+ * Returns NULL on error.
+ */
+char *strdup_printf(const char *fmt, ...);
+
#endif /* LABWC_STRING_HELPERS_H */
// SPDX-License-Identifier: GPL-2.0-only
#include <ctype.h>
+#include <stdarg.h>
#include <stdio.h>
#include <string.h>
+#include "common/mem.h"
#include "common/string-helpers.h"
static void
}
*p = '\0';
}
+
+char *
+strdup_printf(const char *fmt, ...)
+{
+ size_t size = 0;
+ char *p = NULL;
+ va_list ap;
+
+ va_start(ap, fmt);
+ int n = vsnprintf(p, size, fmt, ap);
+ va_end(ap);
+
+ if (n < 0) {
+ return NULL;
+ }
+
+ size = (size_t)n + 1;
+ p = xzalloc(size);
+
+ va_start(ap, fmt);
+ n = vsnprintf(p, size, fmt, ap);
+ va_end(ap);
+
+ if (n < 0) {
+ free(p);
+ return NULL;
+ }
+ return p;
+}
int nr_workspaces = wl_list_length(&rc.workspace_config.workspaces);
if (nr_workspaces < rc.workspace_config.min_nr_workspaces) {
struct workspace *workspace;
- char workspace_name[32];
for (int i = nr_workspaces; i < rc.workspace_config.min_nr_workspaces; i++) {
workspace = znew(*workspace);
- snprintf(workspace_name, sizeof(workspace_name), "Workspace %d", i + 1);
- workspace->name = xstrdup(workspace_name);
+ workspace->name = strdup_printf("Workspace %d", i + 1);
wl_list_append(&rc.workspace_config.workspaces, &workspace->link);
}
}
if (string_empty(dir) || string_empty(filename)) {
return NULL;
}
- int len = strlen(dir) + strlen(filename) + 2;
- char *buffer = znew_n(char, len);
- strcat(buffer, dir);
- strcat(buffer, "/");
- strcat(buffer, filename);
- return buffer;
+ return strdup_printf("%s/%s", dir, filename);
}
static void
}
wlr_log(WLR_INFO, "Updating dbus execution environment");
- char *cmd;
- const char *dbus = "dbus-update-activation-environment ";
- const char *systemd = "systemctl --user import-environment ";
-
- cmd = znew_n(char, strlen(dbus) + strlen(env_keys) + 1);
- strcat(cmd, dbus);
- strcat(cmd, env_keys);
+ char *cmd = strdup_printf("dbus-update-activation-environment %s", env_keys);
spawn_async_no_shell(cmd);
free(cmd);
- cmd = znew_n(char, strlen(systemd) + strlen(env_keys) + 1);
- strcat(cmd, systemd);
- strcat(cmd, env_keys);
+ cmd = strdup_printf("systemctl --user import-environment %s", env_keys);
spawn_async_no_shell(cmd);
free(cmd);
}
goto out;
}
wlr_log(WLR_INFO, "run autostart file %s", autostart);
- int len = strlen(autostart) + 4;
- char *cmd = znew_n(char, len);
- strcat(cmd, "sh ");
- strcat(cmd, autostart);
+ char *cmd = strdup_printf("sh %s", autostart);
spawn_async_no_shell(cmd);
free(cmd);
out: