Skip to content
Myr

Add xmalloc.h and xsnprintf.h and use to improve/simplify error handling

Before adoption: this commit came in with the history the project adopted, so no landing records it.

The IGNORE_WARNING() and HAS_EXTENSION() macros added here were already referenced in debug.h, but neither were expanded anywhere prior to this commit. This is (I assume) because that file was copied verbatim from foot, in commit 20e05303401664a6c26785ed6eafc7ee599d8eb8.

authored by Craig Barnes · committed by Daniel Eklöf · parent 25c7c96 · Browse files · 27 files+541 added−401 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

27 files+541 added−401 removed

  • other:+541 added−401 removed

27 files+541 added−401 removed

modified:application.c+14 added-26 removed
14 unmodified lines
15#define LOG_MODULE "application"16#define LOG_ENABLE_DBG 017#include "log.h"18#include "char32.h"19#include "xmalloc.h"2020static bool21static void22push_argv(char ***argv, size_t *size, char *arg, size_t *argc)23{24 if (arg != NULL && arg[0] == '%')24 return true;25 return;2627 if (*argc >= *size) {28 size_t new_size = *size > 0 ? 2 * *size : 10;28 char **new_argv = reallocarray(*argv, new_size, sizeof(new_argv[0]));2930 if (new_argv == NULL)31 return false;3233 *argv = new_argv;29 *argv = xreallocarray(*argv, new_size, sizeof(char*));30 *size = new_size;31 }3233 (*argv)[(*argc)++] = arg;38 return true;34}3536static bool37tokenize_cmdline(char *cmdline, char ***argv)
59 unmodified lines
97 */98 open_quote = 0;99 *p = '\0';100106 if (!push_argv(argv, &argv_size, search_start, &idx))107 goto err;101 push_argv(argv, &argv_size, search_start, &idx);102103 search_start = p + 1;104 } else if (*p == ' ' && open_quote == 0) {105 /* we must not be in an argument right now106 * check if we can close the arg at p (exclusive) */107 if (p > search_start) {108 *p = '\0';115 if (!push_argv(argv, &argv_size, search_start, &idx))116 goto err;109 push_argv(argv, &argv_size, search_start, &idx);110 }111 search_start = p + 1;112 }113 }
5 unmodified lines
119 goto err;120 }121122 /* edge case: argument terminated by \0 */130 if (p > search_start) {131 if (!push_argv(argv, &argv_size, search_start, &idx))132 goto err;133 }123 if (p > search_start)124 push_argv(argv, &argv_size, search_start, &idx);125135 if (!push_argv(argv, &argv_size, NULL, &idx))136 goto err;137126 push_argv(argv, &argv_size, NULL, &idx);127 return true;128129err:130 free(*argv);
25 unmodified lines
156 char *execute_dest;157 size_t execute_len = strlen(execute);158 if (launch_prefix != NULL) {159 size_t launch_len = strlen(launch_prefix);171 unescaped = malloc(launch_len + execute_len + 2 /* whitespace + null terminator */);172 sprintf(unescaped, "%s ", launch_prefix);160 unescaped = xmalloc(launch_len + execute_len + 2 /* whitespace + null terminator */);161 memcpy(unescaped, launch_prefix, launch_len);162 unescaped[launch_len] = ' ';163 execute_dest = unescaped + launch_len + 1;164 if (id != NULL) {165 setenv("FUZZEL_DESKTOP_FILE_ID", id, 1);166 } else {167 LOG_WARN("No Desktop File ID, not setting FUZZEL_DESKTOP_FILE_ID");168 }169 } else {180 unescaped = malloc(execute_len + 1);170 unescaped = xmalloc(execute_len + 1);171 execute_dest = unescaped;172 }173174 /* Substitute escape sequences for their literal character values */
127 unmodified lines
302303struct application_list *304applications_init(void)305{316 struct application_list *ret = calloc(1, sizeof(*ret));317 if (ret == NULL)318 return NULL;306 struct application_list *ret = xcalloc(1, sizeof(*ret));307308 if (mtx_init(&ret->lock, mtx_plain) != thrd_success) {309 LOG_ERR("failed to instantiate application list mutex");310 free(ret);
84 unmodified lines
modified:char32.c+12 added-18 removed
14 unmodified lines
1516#define LOG_MODULE "char32"17#define LOG_ENABLE_DBG 018#include "log.h"19#include "xmalloc.h"2021/*22 * For now, assume we can map directly to the corresponding wchar_t23 * functions. This is true if:
36 unmodified lines
60 return (char32_t *)wcscpy((wchar_t *)dest, (const wchar_t *)src);61}6263char32_t *64c32memcpy(char32_t *dest, const char32_t *src, size_t n)65{66 return (char32_t *)wmemcpy((wchar_t *)dest, (const wchar_t *)src, n);67}6869char32_t *70c32cat(char32_t *dest, const char32_t *src)71{72 return (char32_t *)wcscat((wchar_t *)dest, (const wchar_t *)src);73}
116 unmodified lines
190 return NULL;191192 const size_t src_len = strlen(src);193187 char32_t *ret = malloc((src_len + 1) * sizeof(ret[0]));188 if (ret == NULL)189 return NULL;194 char32_t *ret = xmalloc((src_len + 1) * sizeof(ret[0]));195196 mbstate_t ps = {0};197 char32_t *out = ret;198 const char *in = src;
16 unmodified lines
215 }216217 *out = U'\0';218214 ret = reallocarray(ret, chars + 1, sizeof(ret[0]));215 return ret;219 return xreallocarray(ret, chars + 1, sizeof(ret[0]));220221err:222 free(ret);223 return NULL;
7 unmodified lines
231232 const size_t src_len = c32len(src);233234 size_t allocated = src_len + 1;231 char *ret = malloc(allocated);232 if (ret == NULL)233 return NULL;235 char *ret = xmalloc(allocated);236237 mbstate_t ps = {0};238 char *out = ret;239 const char32_t *const end = src + src_len + 1;
11 unmodified lines
251 }252253 if (bytes + rc > allocated) {254 allocated *= 2;253 char *new_ret = realloc(ret, allocated);254 if (new_ret == NULL) {255 free(ret);256 return NULL;257 }258 ret = new_ret;255 ret = xrealloc(ret, allocated);256 out = &ret[bytes];257 }258259 for (size_t i = 0; i < rc; i++, out++)
2 unmodified lines
262 bytes += rc;263 }264265 assert(ret[bytes - 1] == '\0');269 char *new_ret = realloc(ret, bytes);270 if (new_ret != NULL)271 ret = new_ret;272 return ret;266 return xrealloc(ret, bytes);267268err:269 free(ret);270 return NULL;
19 unmodified lines
modified:char32.h+1 added
7 unmodified lines
8size_t c32len(const char32_t *s);9int c32cmp(const char32_t *s1, const char32_t *s2);10int c32casecmp(const char32_t *s1, const char32_t *s2);11char32_t *c32cpy(char32_t *dest, const char32_t *src);12char32_t *c32memcpy(char32_t *dest, const char32_t *src, size_t n);13char32_t *c32cat(char32_t *dest, const char32_t *src);14char32_t *c32dup(const char32_t *s);15char32_t *c32chr(const char32_t *s, char32_t c);16
11 unmodified lines
modified:clipboard.c+6 added-4 removed
10 unmodified lines
1112#define LOG_MODULE "clipboard"13#define LOG_ENABLE_DBG 114#include "log.h"15#include "macros.h"16#include "prompt.h"17#include "uri.h"18#include "wayland.h"19#include "xmalloc.h"2021static const char *const mime_type_map[] = {22 [DATA_OFFER_MIME_UNSET] = NULL,23 [DATA_OFFER_MIME_TEXT_PLAIN] = "text/plain",
45 unmodified lines
69{70 enum data_offer_mime_type mime_type = DATA_OFFER_MIME_UNSET;7172 /* Translate offered mime type to our mime type enum */71 for (size_t i = 0; i < sizeof(mime_type_map) / sizeof(mime_type_map[0]); i++) {73 for (size_t i = 0; i < ALEN(mime_type_map); i++) {74 if (mime_type_map[i] == NULL)75 continue;7677 if (strcmp(_mime_type, mime_type_map[i]) == 0) {
176 unmodified lines
254 "even though we rejected the drag-and-drop");255 return;256 }257256 struct dnd_context *ctx = malloc(sizeof(*ctx));258 struct dnd_context *ctx = xmalloc(sizeof(*ctx));259 *ctx = (struct dnd_context){260 .seat = seat,261 .data_offer = clipboard->data_offer,262 };
196 unmodified lines
459fdm_receive_decoder_uri(struct clipboard_receive *ctx, char *data, size_t size)460{461 while (ctx->buf.idx + size > ctx->buf.sz) {462 size_t new_sz = ctx->buf.sz == 0 ? size : 2 * ctx->buf.sz;461 ctx->buf.data = realloc(ctx->buf.data, new_sz);463 ctx->buf.data = xrealloc(ctx->buf.data, new_sz);464 ctx->buf.sz = new_sz;465 }466467 memcpy(&ctx->buf.data[ctx->buf.idx], data, size);
147 unmodified lines
615 LOG_ERRNO("failed to arm clipboard timeout timer");616 goto err;617 }618617 ctx = malloc(sizeof(*ctx));619 ctx = xmalloc(sizeof(*ctx));620 *ctx = (struct clipboard_receive) {621 .seat = seat,622 .read_fd = read_fd,623 .timeout_fd = timeout_fd,
129 unmodified lines
modified:config.c+37 added-52 removed
17 unmodified lines
18#define LOG_MODULE "config"19#define LOG_ENABLE_DBG 020#include "log.h"21#include "key-binding.h"22#include "macros.h"23#include "xmalloc.h"24#include "xsnprintf.h"2523#define ALEN(v) (sizeof(v) / sizeof((v)[0]))2426const struct anchors_map anchors_map[] = {27 {"top-left", ANCHOR_TOP_LEFT},28 {"top", ANCHOR_TOP},29 {"top-right", ANCHOR_TOP_RIGHT},
87 unmodified lines
117{118 char *formatted_msg = NULL;119 va_list va;120 va_start(va, fmt);120 if (vasprintf(&formatted_msg, fmt, va) < 0) {121 va_end(va);122 return;123 }124121 int ret = vasprintf(&formatted_msg, fmt, va);122 va_end(va);123124 if (unlikely(ret < 0))125 return;126127 bool print_dot = ctx->key != NULL;128 bool print_colon = ctx->value != NULL;129130 if (!print_dot)
18 unmodified lines
149 char *formatted_msg;150 int ret = vasprintf(&formatted_msg, fmt, va);151 va_end(va);152153 if (ret < 0)153 if (unlikely(ret < 0))154 return;155156 bool print_dot = ctx->key != NULL;157 bool print_colon = ctx->value != NULL;
28 unmodified lines
186 const char *home_dir = getenv("HOME");187 char *xdg_config_dirs_copy = NULL;188189 /* First, check XDG_CONFIG_HOME (or .config, if unset) */190 if (xdg_config_home != NULL && xdg_config_home[0] != '\0' &&191 xdg_config_home[0] == '/') {192 if (asprintf(&path, "%s/fuzzel/fuzzel.ini", xdg_config_home) < 0) {193 LOG_ERRNO("failed to build fuzzel.ini path");194 goto done;195 }190 if (xdg_config_home != NULL && xdg_config_home[0] == '/') {191 path = xstrjoin(xdg_config_home, "/fuzzel/fuzzel.ini");192 } else if (home_dir != NULL) {197 if (asprintf(&path, "%s/.config/fuzzel/fuzzel.ini", home_dir) < 0) {198 LOG_ERRNO("failed to build fuzzel.ini path");199 goto done;200 }193 path = xstrjoin(home_dir, "/.config/fuzzel/fuzzel.ini");194 }195196 if (path != NULL) {197 int fd = open(path, O_RDONLY | O_CLOEXEC);
5 unmodified lines
203 }204 }205206 xdg_config_dirs_copy = xdg_config_dirs != NULL && xdg_config_dirs[0] != '\0'214 ? strdup(xdg_config_dirs)215 : strdup("/etc/xdg");207 ? xstrdup(xdg_config_dirs)208 : xstrdup("/etc/xdg");209210 if (xdg_config_dirs_copy == NULL || xdg_config_dirs_copy[0] == '\0')211 goto done;212
1 unmodified line
214 conf_dir != NULL;215 conf_dir = strtok(NULL, ":"))216 {217 free(path);225 path = NULL;226227 if (asprintf(&path, "%s/fuzzel/fuzzel.ini", conf_dir) < 0) {228 LOG_ERRNO("failed to build fuzzel.ini path");229 goto done;230 }231218 path = xstrjoin(conf_dir, "/fuzzel/fuzzel.ini");219 int fd = open(path, O_RDONLY | O_CLOEXEC);220 if (fd >= 0) {221 ret = (struct config_file){.path = path, .fd = fd};222 path = NULL;
26 unmodified lines
249 /* Handle "none" separately because e.g. none+shift is nonsense */250 if (strncmp(text, "none", len) == 0)251 return true;252266 char *copy = strndup(text, len);253 char *copy = xstrndup(text, len);254255 for (char *tok_ctx = NULL, *key = strtok_r(copy, "+", &tok_ctx);256 key != NULL;257 key = strtok_r(NULL, "+", &tok_ctx))
70 unmodified lines
328 }329330 struct config_key_binding new_combos[combo_count];331345 char *copy = strdup(ctx->value);332 char *copy = xstrdup(ctx->value);333 size_t idx = 0;334335 for (char *tok_ctx = NULL, *combo = strtok_r(copy, " ", &tok_ctx);336 combo != NULL;
33 unmodified lines
370 }371372 remove_from_key_bindings_list(bindings, action);373387 bindings->arr = reallocarray(374 bindings->arr = xreallocarray(375 bindings->arr,376 bindings->count + combo_count, sizeof(bindings->arr[0]));377378 memcpy(&bindings->arr[bindings->count],
22 unmodified lines
401402static char *403modifiers_to_str(const struct config_key_modifiers *mods)404{418 char *ret = NULL;419 if (asprintf(&ret,420 "%s%s%s%s",421 mods->ctrl ? XKB_MOD_NAME_CTRL "+" : "",422 mods->alt ? XKB_MOD_NAME_ALT "+": "",423 mods->super ? XKB_MOD_NAME_LOGO "+": "",424 mods->shift ? XKB_MOD_NAME_SHIFT "+": "") < 0)425 return NULL;405 return xasprintf(406 "%s%s%s%s",407 mods->ctrl ? XKB_MOD_NAME_CTRL "+" : "",408 mods->alt ? XKB_MOD_NAME_ALT "+": "",409 mods->super ? XKB_MOD_NAME_LOGO "+": "",410 mods->shift ? XKB_MOD_NAME_SHIFT "+": ""411 );426 return ret;412}413414static bool415resolve_key_binding_collisions(struct config *conf, const char *section_name,
119 unmodified lines
535static bool536value_to_str(struct context *ctx, char **res)537{538 free(*res);554 *res = strdup(ctx->value);539 *res = xstrdup(ctx->value);540 return true;541}542543static bool
150 unmodified lines
694 size_t idx = 0;695 assert(size < sizeof(valid_values));696697 for (size_t i = 0; i < count; i++)713 idx += snprintf(&valid_values[idx], size - idx, "'%s', ", value_map[i]);698 idx += xsnprintf(&valid_values[idx], size - idx, "'%s', ", value_map[i]);699700 if (count > 0)701 valid_values[idx - 2] = '\0';702
107 unmodified lines
810 "enum is not 32-bit");811812 enum match_fields match_fields = 0;813829 char *copy = strdup(value);814 char *copy = xstrdup(value);815 for (const char *field = strtok(copy, ",");816 field != NULL;817 field = strtok(NULL, ","))818 {
11 unmodified lines
830 };831832 enum match_fields field_value = 0;833849 for (size_t i = 0; i < sizeof(map) / sizeof(map[0]); i++) {834 for (size_t i = 0; i < ALEN(map); i++) {835 if (strcmp(field, map[i].name) == 0) {836 field_value = map[i].value;837 break;838 }
427 unmodified lines
1266 } else \1267 continue; \1268 }12691285 char *section_name = strdup("main");1270 char *section_name = xstrdup("main");12711272 struct context context = {1273 .conf = conf,1274 .section = section_name,
85 unmodified lines
1360 error_or_continue();1361 }13621363 free(section_name);1379 section_name = strdup(key_value);1364 section_name = xstrdup(key_value);1365 context.section = section_name;13661367 /* Process next line */1368 continue;
199 unmodified lines
1568 {BIND_ACTION_CUSTOM_19, m_alt, {{XKB_KEY_parenleft}}},1569 };15701571 conf->key_bindings.count = ALEN(bindings);1587 conf->key_bindings.arr = malloc(sizeof(bindings));1572 conf->key_bindings.arr = xmalloc(sizeof(bindings));1573 memcpy(conf->key_bindings.arr, bindings, sizeof(bindings));1574}15751576bool
2 unmodified lines
1579{1580 bool ret = !errors_are_fatal;1581 *conf = (struct config) {1582 .output = NULL,1598 .prompt = c32dup(U"> "),1599 .placeholder = c32dup(U""),1600 .search_text = c32dup(U""),1583 .prompt = xc32dup(U"> "),1584 .placeholder = xc32dup(U""),1585 .search_text = xc32dup(U""),1586 .match_fields = MATCH_FILENAME | MATCH_NAME | MATCH_GENERIC,1587 .password_mode = {1588 .character = U'\0',1589 .enabled = false,1590 },1591 .terminal = NULL,1592 .launch_prefix = NULL,1608 .font = strdup("monospace"),1593 .font = xstrdup("monospace"),1594 .use_bold = false,1595 .dpi_aware = DPI_AWARE_AUTO,1596 .render_worker_count = sysconf(_SC_NPROCESSORS_ONLN),1597 .match_worker_count = sysconf(_SC_NPROCESSORS_ONLN),1598 .icons_enabled = true,1614 .icon_theme = strdup("hicolor"),1599 .icon_theme = xstrdup("hicolor"),1600 .hide_when_prompt_empty = false,1601 .actions_enabled = false,1602 .match_mode = MATCH_MODE_FZF,1603 .sort_result = true,
68 unmodified lines
1672 LOG_ERRNO("%s: failed to open", conf_path);1673 goto out;1674 }16751691 conf_file.path = strdup(conf_path);1676 conf_file.path = xstrdup(conf_path);1677 conf_file.fd = fd;1678 } else {1679 conf_file = open_config();1680 if (conf_file.fd < 0) {
57 unmodified lines
modified:dmenu.c+13 added-25 removed
15 unmodified lines
16#define LOG_ENABLE_DBG 017#include "log.h"18#include "char32.h"19#include "event.h"20#include "macros.h"21#include "xmalloc.h"2223void24dmenu_load_entries(struct application_list *applications, char delim,25 int event_fd, int abort_fd)
1 unmodified line
27 tll(struct application *) entries = tll_init();2829 size_t size = 0;30 size_t alloc_size = 16384;29 char *buffer = malloc(alloc_size);31 char *buffer = xmalloc(alloc_size);3231 if (buffer == NULL) {32 LOG_ERRNO("failed to allocate input buffer");33 return;34 }3536 int flags;37 if ((flags = fcntl(STDIN_FILENO, F_GETFL)) < 0 ||38 fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) < 0)39 {33 int flags = fcntl(STDIN_FILENO, F_GETFL);34 if (flags < 0 || fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) < 0) {35 LOG_ERRNO("failed to set O_NONBLOCK on stdin");36 goto out;37 }38
7 unmodified lines
46 /* Must be last */47 {.fd = abort_fd, .events = POLLIN},48 };4955 size_t count = sizeof(fds) / sizeof(fds[0]);50 size_t count = ALEN(fds);51 if (abort_fd < 0)52 count--;5354 int ret = poll(fds, count, -1);
12 unmodified lines
67 LOG_DBG("increasing input buffer size %zu -> %zu",68 alloc_size, alloc_size * 2);6970 alloc_size *= 2;7677 char *new_buf = realloc(buffer, alloc_size);71 buffer = xrealloc(buffer, alloc_size);78 if (new_buf == NULL) {79 LOG_ERRNO("failed to reallocate input buffer");80 break;81 }8283 buffer = new_buf;72 }7374 ssize_t bytes_read = read(75 STDIN_FILENO, &buffer[size], alloc_size - size - 1);
61 unmodified lines
137 /*138 * 'extra' is "\0icon\x1f" - 6 characters. Require139 * *more* than 6, since icon *name* cannot be empty140 */153 if (extra_len > 6 && memcmp(extra, "\0icon\x1f", 6) == 0)154 icon_name = strndup(extra + 6, delim_at - (extra + 6));141 if (extra_len > 6 && memcmp(extra, "\0icon\x1f", 6) == 0)142 icon_name = xstrndup(extra + 6, delim_at - (extra + 6));143 }144145 LOG_DBG("%s (icon=%s)", buffer, icon_name);146
10 unmodified lines
157 free(icon_name);158 continue;159 }160173 char32_t *lowercase = c32dup(wline);161 char32_t *lowercase = xc32dup(wline);162 for (size_t i = 0; i < c32len(lowercase); i++)163 lowercase[i] = toc32lower(lowercase[i]);164177 struct application *app = malloc(sizeof(*app));165 struct application *app = xmalloc(sizeof(*app));166 *app = (struct application){167 .index = app_idx++,168 .title = wline,169 .title_lowercase = lowercase,
8 unmodified lines
178 if (event_fd >= 0) {179 mtx_lock(&applications->lock);180181 const size_t new_count = applications->count + tll_length(entries);194 applications->v = reallocarray(182 applications->v = xreallocarray(183 applications->v, new_count, sizeof(applications->v[0]));184185 size_t i = applications->count;186 tll_foreach(entries, it) {
17 unmodified lines
204205 mtx_lock(&applications->lock);206207 const size_t new_count = applications->count + tll_length(entries);220 applications->v = reallocarray(208 applications->v = xreallocarray(209 applications->v, new_count, sizeof(applications->v[0]));210211 size_t i = applications->count;212 tll_foreach(entries, it) {
30 unmodified lines
modified:fdm.c+3 added-2 removed
10 unmodified lines
1112#define LOG_MODULE "fdm"13#define LOG_ENABLE_DBG 014#include "log.h"15#include "xmalloc.h"1617struct handler {18 int fd;19 int events;
17 unmodified lines
37 LOG_ERRNO("failed to create epoll FD");38 return NULL;39 }4040 struct fdm *fdm = malloc(sizeof(*fdm));41 struct fdm *fdm = xmalloc(sizeof(*fdm));42 *fdm = (struct fdm){43 .epoll_fd = epoll_fd,44 .is_polling = false,45 .fds = tll_init(),
31 unmodified lines
77 }78 }79#endif8080 struct handler *fd_data = malloc(sizeof(*fd_data));81 struct handler *fd_data = xmalloc(sizeof(*fd_data));82 *fd_data = (struct handler) {83 .fd = fd,84 .events = events,85 .callback = handler,
154 unmodified lines
modified:icon.c+16 added-24 removed
27 unmodified lines
28#define LOG_MODULE "icon"29#define LOG_ENABLE_DBG 030#include "log.h"31#include "xdg.h"32#include "xmalloc.h"33#include "xsnprintf.h"3435typedef tll(char *) theme_names_t;3637static void
58 unmodified lines
96 context = NULL;97 type = ICON_DIR_THRESHOLD;98 threshold = 2;9998 section = malloc(len - 2 + 1);100 section = xmalloc(len - 2 + 1);101 memcpy(section, &line[1], len - 2);102 section[len - 2] = '\0';103 free(line);104 continue;
8 unmodified lines
113 char *ctx = NULL;114 for (const char *theme_name = strtok_r(value, ",", &ctx);115 theme_name != NULL; theme_name = strtok_r(NULL, ",", &ctx))116 {115 tll_push_back(*themes_to_load, strdup(theme_name));117 tll_push_back(*themes_to_load, xstrdup(theme_name));118 }119 }120121 if (strcasecmp(key, "directories") == 0) {
1 unmodified line
123 for (const char *d = strtok_r(value, ",", &save);124 d != NULL;125 d = strtok_r(NULL, ",", &save))126 {125 struct icon_dir dir = {.path = strdup(d)};127 struct icon_dir dir = {.path = xstrdup(d)};128 tll_push_back(theme->dirs, dir);129 }130 }131
9 unmodified lines
141 else if (strcasecmp(key, "scale") == 0)142 sscanf(value, "%d", &scale);143144 else if (strcasecmp(key, "context") == 0)143 context = strdup(value);145 context = xstrdup(value);146147 else if (strcasecmp(key, "threshold") == 0)148 sscanf(value, "%d", &threshold);149
43 unmodified lines
193load_theme_in(const char *dir, struct icon_theme *theme,194 theme_names_t *themes_to_load)195{196 char path[PATH_MAX];195 snprintf(path, sizeof(path), "%s/index.theme", dir);197 xsnprintf(path, sizeof(path), "%s/index.theme", dir);198199 FILE *index = fopen(path, "r");200 if (index == NULL)201 return false;
26 unmodified lines
228 sprintf(path, "%s/icons/%s", dir_it->item.path, theme_name);229230 struct icon_theme theme = {0};231 if (load_theme_in(path, &theme, themes_to_load)) {230 theme.name = strdup(theme_name);232 theme.name = xstrdup(theme_name);233 tll_push_back(*themes, theme);234 }235 }236}
7 unmodified lines
244245 /* List of themes to try to load. This list will be appended to as246 * we go, and find 'Inherits' values in the theme index files. */247 theme_names_t themes_to_load = tll_init();246 tll_push_back(themes_to_load, strdup(name));248 tll_push_back(themes_to_load, xstrdup(name));249250 xdg_data_dirs_t dirs = xdg_data_dirs();251252 while (tll_length(themes_to_load) > 0) {
127 unmodified lines
380381static bool382svg(struct icon *icon, const char *path)383{382 icon->path = strdup(path);384 icon->path = xstrdup(path);385 icon->type = ICON_SVG;386 icon->svg = NULL;387 return true;388}389390static bool391png(struct icon *icon, const char *path)392{391 icon->path = strdup(path);393 icon->path = xstrdup(path);394 icon->type = ICON_PNG;395 icon->png = NULL;396 return true;397}
132 unmodified lines
530 if (png(&app->icon, app->icon.name))531 LOG_DBG("%s: abslute path PNG", app->icon.name);532 }533 } else {532 size_t file_name_len = strlen(app->icon.name) + 4;533 char *file_name = malloc(file_name_len + 1);534 strcpy(file_name, app->icon.name);535 strcat(file_name, ".xxx");536534 char *file_name = xstrjoin(app->icon.name, ".xxx");535 struct icon_data data = {536 .name = app->icon.name,537 .app = app,538 .file_name = file_name,541 .file_name_len = file_name_len,539 .file_name_len = strlen(file_name),540 .min_diff = {.diff = INT_MAX},541 };542 tll_push_back(icons, data);543 }
103 unmodified lines
647 ? ICON_SVG : ICON_PNG;648 continue;649 }650653 char *full_path = malloc(654 strlen(xdg_dir->path) + 1 +655 5 + 1 + /* “icons” */656 strlen(theme->name) + 1 +657 strlen(icon_dir->path) + 1 +658 len + 1);651 char *full_path = xasprintf(652 "%s/icons/%s/%s/%s",653 xdg_dir->path, theme->name, icon_dir->path, path);654660 sprintf(full_path, "%s/icons/%s/%s/%s",661 xdg_dir->path, theme->name, icon_dir->path, path);662655 if ((path[len - 3] == 's' &&656 svg(&icon->app->icon, full_path)) ||657 (path[len - 3] == 'p' &&658 png(&icon->app->icon, full_path)))
112 unmodified lines
modified:key-binding.c+3 added-3 removed
4 unmodified lines
56#define LOG_MODULE "key-binding"7#define LOG_ENABLE_DBG 08#include "log.h"9#include "macros.h"10#include "xmalloc.h"1110#define ALEN(v) (sizeof(v) / sizeof((v)[0]))1112struct key_set {13 struct key_binding_set public;14 const struct config *conf;15 const struct seat *seat;
11 unmodified lines
2728struct kb_manager *29kb_manager_new(void)30{31 struct kb_manager *mgr = calloc(1, sizeof(*mgr));31 struct kb_manager *mgr = xcalloc(1, sizeof(*mgr));32 return mgr;33}3435void
341 unmodified lines
modified:log.c+4 added-5 removed
8 unmodified lines
9#include <string.h>10#include <syslog.h>11#include <unistd.h>12#include <assert.h>13#include "macros.h"14#include "xsnprintf.h"1514#define ALEN(v) (sizeof(v) / sizeof((v)[0]))15#define UNUSED __attribute__((unused))1616static bool colorize = false;17static bool do_syslog = false;18static enum log_class log_level = LOG_CLASS_NONE;19
56 unmodified lines
76 const char *prefix = log_level_map[log_class].log_prefix;77 unsigned int class_clr = log_level_map[log_class].color;7879 char clr[16];81 snprintf(clr, sizeof(clr), "\033[%um", class_clr);80 xsnprintf(clr, sizeof(clr), "\033[%um", class_clr);81 fprintf(stderr, "%s%s%s: ", colorize ? clr : "", prefix, colorize ? "\033[0m" : "");8283 if (colorize)84 fputs("\033[2m", stderr);
132 unmodified lines
217218 for (size_t i = 0, pos = 0, n = map_len(); i < n; i++) {219 const char *entry = log_level_map[i].name;220 const char *delim = (i + 1 < n) ? ", " : "";222 pos += snprintf(buf + pos, sizeof(buf) - pos, "'%s'%s", entry, delim);221 pos += xsnprintf(buf + pos, sizeof(buf) - pos, "'%s'%s", entry, delim);222 }223224 return buf;225}
modified:macros.h+58 added
1#pragma once23#define ALEN(v) (sizeof(v) / sizeof((v)[0]))4#define DO_PRAGMA(x) _Pragma(#x)5#define VERCMP(x, y, cx, cy) ((cx > x) || ((cx == x) && (cy >= y)))67#ifdef __has_include8 #define HAS_INCLUDE(x) __has_include(x)
18 unmodified lines
27#else28 #define HAS_BUILTIN(x) 029#endif3031// __has_extension() is a Clang macro used to determine if a feature is32// available even if not standardized in the current "-std" mode.33#ifdef __has_extension34 #define HAS_EXTENSION(x) __has_extension(x)35#else36 // Clang versions prior to 3.0 only supported __has_feature()37 #define HAS_EXTENSION(x) HAS_FEATURE(x)38#endif3940#if defined(__GNUC__) && defined(__GNUC_MINOR__)41 #define GNUC_AT_LEAST(x, y) VERCMP(x, y, __GNUC__, __GNUC_MINOR__)42#else43 #define GNUC_AT_LEAST(x, y) 0
4 unmodified lines
48#else49 #define UNUSED50#endif5152#if GNUC_AT_LEAST(3, 0) || HAS_ATTRIBUTE(malloc)53 #define MALLOC __attribute__((__malloc__))54#else55 #define MALLOC56#endif5758#if GNUC_AT_LEAST(3, 0) || HAS_ATTRIBUTE(format)59 #define PRINTF(x) __attribute__((__format__(__printf__, (x), (x + 1))))60 #define VPRINTF(x) __attribute__((__format__(__printf__, (x), 0)))61#else
22 unmodified lines
84#else85 #define COLD86#endif8788#if GNUC_AT_LEAST(3, 3) || HAS_ATTRIBUTE(nonnull)89 #define NONNULL_ARGS __attribute__((__nonnull__))90 #define NONNULL_ARG(...) __attribute__((__nonnull__(__VA_ARGS__)))91#else92 #define NONNULL_ARGS93 #define NONNULL_ARG(...)94#endif9596#if GNUC_AT_LEAST(3, 4) || HAS_ATTRIBUTE(warn_unused_result)97 #define WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))98#else99 #define WARN_UNUSED_RESULT100#endif101102#if GNUC_AT_LEAST(4, 3) || HAS_ATTRIBUTE(hot)103 #define HOT __attribute__((__hot__))104#else105 #define HOT
3 unmodified lines
109 #define UNREACHABLE() __builtin_unreachable()110#else111 #define UNREACHABLE()112#endif113114#if GNUC_AT_LEAST(5, 0) || HAS_ATTRIBUTE(returns_nonnull)115 #define RETURNS_NONNULL __attribute__((__returns_nonnull__))116#else117 #define RETURNS_NONNULL118#endif119120#define XMALLOC MALLOC RETURNS_NONNULL WARN_UNUSED_RESULT121#define XSTRDUP XMALLOC NONNULL_ARGS122123#ifdef __clang__124 #define IGNORE_WARNING(wflag) \125 DO_PRAGMA(clang diagnostic push) \126 DO_PRAGMA(clang diagnostic ignored "-Wunknown-pragmas") \127 DO_PRAGMA(clang diagnostic ignored "-Wunknown-warning-option") \128 DO_PRAGMA(clang diagnostic ignored wflag)129 #define UNIGNORE_WARNINGS DO_PRAGMA(clang diagnostic pop)130#elif GNUC_AT_LEAST(4, 6)131 #define IGNORE_WARNING(wflag) \132 DO_PRAGMA(GCC diagnostic push) \133 DO_PRAGMA(GCC diagnostic ignored "-Wpragmas") \134 DO_PRAGMA(GCC diagnostic ignored wflag)135 #define UNIGNORE_WARNINGS DO_PRAGMA(GCC diagnostic pop)136#else137 #define IGNORE_WARNING(wflag)138 #define UNIGNORE_WARNINGS139#endif
modified:main.c+24 added-30 removed
36 unmodified lines
37#include "shm.h"38#include "version.h"39#include "wayland.h"40#include "xdg.h"41#include "xmalloc.h"42#include "xsnprintf.h"4344#define max(x, y) ((x) > (y) ? (x) : (y))4546struct context {
104 unmodified lines
151 int count;152 sscanf(count_str, "%u", &count);153154 struct cache_entry entry = {153 .id = dmenu ? NULL : strdup(id),155 .id = dmenu ? NULL : xstrdup(id),156 .title = dmenu ? ambstoc32(id) : NULL,157 .count = count,158 };159 tll_push_back(cache_entries, entry);
124 unmodified lines
284static const char *285version_and_features(void)286{287 static char buf[256];286 snprintf(buf, sizeof(buf), "version: %s %ccairo %cpng %csvg%s %cassertions",288 xsnprintf(buf, sizeof(buf), "version: %s %ccairo %cpng %csvg%s %cassertions",289 FUZZEL_VERSION,290#if defined(FUZZEL_ENABLE_CAIRO)291 '+',292#else
186 unmodified lines
479 const char *wayland_display = getenv("WAYLAND_DISPLAY");480 if (wayland_display == NULL)481 return NULL;482481 #define path_fmt "%s/fuzzel-%s.lock"482 int chars = snprintf(NULL, 0, path_fmt, xdg_runtime_dir, wayland_display);483484 char *path = malloc(chars + 1);485 snprintf(path, chars + 1, path_fmt, xdg_runtime_dir, wayland_display);486 #undef path_fmt487483 char *path = xasprintf("%s/fuzzel-%s.lock", xdg_runtime_dir, wayland_display);484 LOG_DBG("lock file: %s", path);485 return path;486}487
39 unmodified lines
527528 if (filter_desktop) {529 char *xdg_current_desktop = getenv("XDG_CURRENT_DESKTOP");530 if (xdg_current_desktop && strlen(xdg_current_desktop) != 0) {535 xdg_current_desktop = strdup(xdg_current_desktop);531 xdg_current_desktop = xstrdup(xdg_current_desktop);532 for (char *desktop = strtok_r(xdg_current_desktop, ":", &saveptr);533 desktop != NULL;534 desktop = strtok_r(NULL, ":", &saveptr))535 {540 tll_push_back(desktops, strdup(desktop));536 tll_push_back(desktops, xstrdup(desktop));537 }538 free(xdg_current_desktop);539 }540 }
326 unmodified lines
867 setlocale(LC_MESSAGES, "");868869 /* Auto-enable dmenu mode if invoked through a ‘dmenu’ symlink */870 if (argv[0] != NULL) {875 char *copy = strdup(argv[0]);876 if (copy != NULL) {877 const char *name = basename(copy);878 if (name != NULL && strcmp(name, "dmenu") == 0) {879 cmdline_overrides.conf.dmenu.enabled = true;880 cmdline_overrides.dmenu_enabled_set = true;881 }882883 free(copy);871 char *copy = xstrdup(argv[0]);872 const char *name = basename(copy);873 if (name != NULL && strcmp(name, "dmenu") == 0) {874 cmdline_overrides.conf.dmenu.enabled = true;875 cmdline_overrides.dmenu_enabled_set = true;876 }877878 free(copy);879 }880881 while (true) {882 int c = getopt_long(argc, argv, ":o:f:D:IF:ia:l:w:x:y:p:P:b:t:m:s:S:M:B:r:C:T:dRvh", longopts, NULL);
83 unmodified lines
966 f = strtok(NULL, ", "))967 {968 enum match_fields field = 0;969976 for (size_t i = 0; i < sizeof(map) / sizeof(map[0]); i++) {970 for (size_t i = 0; i < ALEN(map); i++) {971 if (strcmp(f, map[i].name) == 0) {972 field = map[i].value;973 break;974 }
2 unmodified lines
977 if (field > 0)978 cmdline_overrides.conf.match_fields |= field;979 else {980 char valid_names[128] = {0};987 int idx = 0;988 for (size_t i = 0; i < sizeof(map) / sizeof(map[0]); i++) {989 idx += snprintf(981 size_t idx = 0;982 for (size_t i = 0; i < ALEN(map); i++) {983 idx += xsnprintf(984 &valid_names[idx], sizeof(valid_names) - idx,985 "'%s', ", map[i].name);986 }987
644 unmodified lines
16321633 /* Apply command line overrides */1634 if (cmdline_overrides.conf.output != NULL) {1635 free(conf.output);1642 conf.output = strdup(cmdline_overrides.conf.output);1636 conf.output = xstrdup(cmdline_overrides.conf.output);1637 }1638 if (cmdline_overrides.conf.prompt != NULL) {1639 free(conf.prompt);1640 conf.prompt = cmdline_overrides.conf.prompt;
18 unmodified lines
1659 : U'*';1660 }1661 if (cmdline_overrides.conf.terminal != NULL) {1662 free(conf.terminal);1669 conf.terminal = strdup(cmdline_overrides.conf.terminal);1663 conf.terminal = xstrdup(cmdline_overrides.conf.terminal);1664 }1665 if (cmdline_overrides.conf.launch_prefix != NULL) {1666 free(conf.launch_prefix);1673 conf.launch_prefix = strdup(cmdline_overrides.conf.launch_prefix);1667 conf.launch_prefix = xstrdup(cmdline_overrides.conf.launch_prefix);1668 }1669 if (cmdline_overrides.conf.font != NULL) {1670 free(conf.font);1677 conf.font = strdup(cmdline_overrides.conf.font);1671 conf.font = xstrdup(cmdline_overrides.conf.font);1672 }1673 if (cmdline_overrides.use_bold_set)1674 conf.use_bold = cmdline_overrides.conf.use_bold;1675 if (cmdline_overrides.conf.icon_theme != NULL) {1676 free(conf.icon_theme);1683 conf.icon_theme = strdup(cmdline_overrides.conf.icon_theme);1677 conf.icon_theme = xstrdup(cmdline_overrides.conf.icon_theme);1678 }1679 if (cmdline_overrides.dpi_aware_set)1680 conf.dpi_aware = cmdline_overrides.conf.dpi_aware;1681 if (cmdline_overrides.match_fields_set)
89 unmodified lines
1771 if (cmdline_overrides.delayed_filter_limit_set)1772 conf.delayed_filter_limit = cmdline_overrides.conf.delayed_filter_limit;1773 if (cmdline_overrides.conf.cache_path != NULL) {1774 free(conf.cache_path);1781 conf.cache_path = strdup(cmdline_overrides.conf.cache_path);1775 conf.cache_path = xstrdup(cmdline_overrides.conf.cache_path);1776 }17771778 if (conf.dmenu.enabled) {1779 /* We don't have any meta data in dmenu mode */
205 unmodified lines
modified:match.c+19 added-48 removed
26 unmodified lines
27#define LOG_ENABLE_DBG 028#include "log.h"29#include "char32.h"30#include "wayland.h"31#include "xmalloc.h"3233#define min(x, y) ((x < y) ? (x) : (y))34#define max(x, y) ((x > y) ? (x) : (y))35
135 unmodified lines
171172 if (pos != NULL) {173 assert(pos_count != NULL);174 (*pos_count)++;174 *pos = reallocarray(*pos, *pos_count, sizeof((*pos)[0]));175 *pos = xreallocarray(*pos, *pos_count, sizeof((*pos)[0]));176 (*pos)[*pos_count - 1].start = longest_match_ofs;177 (*pos)[*pos_count - 1].len = longest_match_len;178 }179
48 unmodified lines
228229 if (src_len < pat_len)230 return NULL;231231 struct levenshtein_matrix **m = calloc(pat_len + 1, sizeof(m[0]));232 struct levenshtein_matrix **m = xcalloc(pat_len + 1, sizeof(m[0]));233 for (size_t i = 0; i < pat_len + 1; i++)233 m[i] = calloc(src_len + 1, sizeof(m[0][0]));234 m[i] = xcalloc(src_len + 1, sizeof(m[0][0]));235236 levenshtein_distance(src, src_len, pat, pat_len, m);237238#if 0
125 unmodified lines
364 size_t fuzzy_min_length, size_t fuzzy_max_length_discrepancy,365 size_t fuzzy_max_distance, uint16_t workers,366 size_t delay_ms, size_t delay_limit)367{367 struct matches *matches = malloc(sizeof(*matches));368 struct matches *matches = xmalloc(sizeof(*matches));369 *matches = (struct matches) {370 .fdm = fdm,371 .prompt = prompt,372 .applications = NULL,
28 unmodified lines
401 goto err_free_semaphores;402 }403404 matches->workers.threads =404 calloc(workers, sizeof(matches->workers.threads[0]));405 xcalloc(workers, sizeof(matches->workers.threads[0]));406406 if (matches->workers.threads == NULL) {407 LOG_ERRNO("failed to allocate match worker threads array");408 goto err_free_semaphores_and_lock;409 }410407 for (size_t i = 0; i < workers; i++) {412 struct thread_context *ctx = malloc(sizeof(*ctx));413 if (ctx == NULL) {414 LOG_ERRNO("failed to allocate match worker thread context");415 goto err_free_semaphores_and_lock;416 }417408 struct thread_context *ctx = xmalloc(sizeof(*ctx));409 *ctx = (struct thread_context){410 .matches = matches,411 .my_id = 1 + i,412 };
106 unmodified lines
519 mtx_unlock(&applications->lock);520 return;521 }522532 matches->matches = reallocarray(523 matches->matches = xreallocarray(524 matches->matches, applications->count, sizeof(matches->matches[0]));525526 const size_t old_size = matches->matches_size;527 const size_t diff = applications->count - old_size;
371 unmodified lines
899 pos[pos_count - 1].len]) {900 /* Extend last match position */901 pos[pos_count - 1].len += match_len;902 } else {912 size_t new_pos_count = pos_count + 1;913 struct match_substring *new_pos =914 reallocarray(pos, new_pos_count, sizeof(new_pos[0]));903 pos_count += 1;904 pos = xreallocarray(pos, pos_count, sizeof(pos[0]));905916 if (new_pos != NULL) {917 pos = new_pos;918 pos_count = new_pos_count;919920 pos[pos_count - 1].start = m - app->title_lowercase;921 pos[pos_count - 1].len = match_len;906 pos[pos_count - 1].start = m - app->title_lowercase;907 pos[pos_count - 1].len = match_len;922 }908 }909 }910911 if (t == 0)
521 unmodified lines
1433 match_comment ? "yes" : "no");14341435 LOG_DBG("match update begin");14361452 char32_t *copy = c32dup(ptext);1453 char32_t **tokens = malloc(sizeof(tokens[0]));1454 size_t *tok_lengths = malloc(sizeof(tok_lengths[0]));14551456 if (copy == NULL || tokens == NULL || tok_lengths == NULL) {1457 LOG_ERR("failed to allocate tokens");1458 goto free_unlock_and_return;1459 }14601437 char32_t *copy = xc32dup(ptext);1438 char32_t **tokens = xmalloc(sizeof(tokens[0]));1439 size_t *tok_lengths = xmalloc(sizeof(tok_lengths[0]));1440 size_t tok_count = 1;1441 tokens[0] = copy;1442 tok_lengths[0] = 0;1443
10 unmodified lines
1454 tokens[tok_count - 1] = p + 1;1455 } else {1456 tok_count++;14571479 char32_t **new_tokens = reallocarray(1480 tokens, tok_count, sizeof(tokens[0]));1458 tokens = xreallocarray(tokens, tok_count, sizeof(tokens[0]));1481 if (new_tokens == NULL)1482 goto free_unlock_and_return;1483 tokens = new_tokens;14591485 size_t *new_tok_lengths = reallocarray(1460 tok_lengths = xreallocarray(1461 tok_lengths, tok_count, sizeof(tok_lengths[0]));1487 if (new_tok_lengths == NULL)1488 goto free_unlock_and_return;1489 tok_lengths = new_tok_lengths;14621463 tokens[tok_count - 1] = p + 1;1464 tok_lengths[tok_count - 1] = 0;1465 }
26 unmodified lines
1492 matches->workers.tok_lengths = tok_lengths;14931494 if (incremental) {1495 matches->workers.old_matches =1524 reallocarray(matches->workers.old_matches,1496 xreallocarray(matches->workers.old_matches,1497 matches->match_count,1498 sizeof(matches->workers.old_matches[0]));14991500 memcpy(matches->workers.old_matches,
66 unmodified lines
15671568 if (matches->selected >= matches->match_count && matches->selected > 0)1569 matches->selected = matches->match_count - 1;15701599free_unlock_and_return:1571 free(tok_lengths);1572 free(tokens);1573 free(copy);1574
28 unmodified lines
1603 {1604 matches->delayed_update_type = DELAYED_FULL_UPDATE;1605 if (arm_delayed_timer(matches))1606 return;1636 } 1607 }16081609 matches_update_internal(matches, false);1610}1611
36 unmodified lines
modified:meson.build+2 added
173 unmodified lines
174 'stride.h',175 'uri.c', 'uri.h',176 'wayland.c', 'wayland.h',177 'xdg.c', 'xdg.h',178 'xmalloc.c', 'xmalloc.h',179 'xsnprintf.c', 'xsnprintf.h',180 wl_proto_src + wl_proto_headers, version,181 dependencies: [math,182 threads,183 pixman,
31 unmodified lines
modified:path.c+6 added-9 removed
13 unmodified lines
14#define LOG_ENABLE_DBG 015#include "log.h"16#include "xdg.h"17#include "char32.h"18#include "xmalloc.h"1920void21path_find_programs(struct application_list *applications)22{
1 unmodified line
2425 if (_path == NULL)26 return ;2727 char *copy = strdup(_path);28 char *copy = xstrdup(_path);29 char *ctx = NULL;30 tll(struct application *) entries = tll_init();3132 for (const char *tok = strtok_r(copy, ":", &ctx);
10 unmodified lines
43 LOG_WARN("failed to open %s's fd from PATH", tok);44 closedir(d);45 continue;46 }46 const size_t path_size = strlen(tok);47 for (const struct dirent *e = readdir(d); e != NULL; e = readdir(d)) {48 if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0)49 continue;50
16 unmodified lines
67 if (already_exist) {68 free(wtitle);69 continue;70 }71 size_t exec_size = path_size + 1 + strlen(e->d_name) + 1;72 char *exec = malloc(exec_size);73 snprintf(exec, exec_size, "%s/%s", tok, e->d_name);7175 char32_t *lowercase = c32dup(wtitle);72 char32_t *lowercase = xc32dup(wtitle);73 for (size_t i = 0; i < c32len(lowercase); i++)74 lowercase[i] = toc32lower(lowercase[i]);7579 struct application *app = malloc(sizeof(*app));76 struct application *app = xmalloc(sizeof(*app));77 *app = (struct application){78 .index = 0, /* Not used in application mode */79 .title = wtitle,80 .title_lowercase = lowercase,81 .title_len = c32len(lowercase),85 .exec = exec,82 .exec = xstrjoin3(tok, "/", e->d_name),83 .visible = true,84 };8586 tll_push_back(entries, app);
2 unmodified lines
89 closedir(d);90 }91 free(copy);9296 applications->v = reallocarray(93 applications->v = xreallocarray(94 applications->v, applications->count + tll_length(entries), sizeof(applications->v[0]));9596 tll_foreach(entries, it) {97 applications->v[applications->count++] = it->item;
4 unmodified lines
modified:png.c+3 added-2 removed
13 unmodified lines
14#define LOG_MODULE "png"15#define LOG_ENABLE_DBG 016#include "log.h"17#include "stride.h"18#include "xmalloc.h"1920static void21png_warning_cb(png_structp png_ptr, png_const_charp warning_msg)22{
108 unmodified lines
131 png_read_update_info(png_ptr, info_ptr);132133 size_t row_bytes __attribute__((unused)) = png_get_rowbytes(png_ptr, info_ptr);134 int stride = stride_for_format_and_width(format, width);134 image_data = malloc(height * stride);135 image_data = xmalloc(height * stride);136137 LOG_DBG("stride=%d, row-bytes=%zu", stride, row_bytes);138 assert(stride >= row_bytes);139139 row_pointers = malloc(height * sizeof(png_bytep));140 row_pointers = xmalloc(height * sizeof(png_bytep));141 for (int i = 0; i < height; i++)142 row_pointers[i] = &image_data[i * stride];143144 png_read_image(png_ptr, row_pointers);
43 unmodified lines
modified:prompt.c+8 added-10 removed
7 unmodified lines
8#define LOG_ENABLE_DBG 09#include "log.h"10#include "char32.h"11#include "wayland.h"12#include "xmalloc.h"1314struct prompt {15 char32_t *prompt;16 char32_t *placeholder;
6 unmodified lines
23 const char32_t *text)24{25 const bool have_initial_text = text != NULL && text[0] != U'\0';2626 struct prompt *prompt = malloc(sizeof(*prompt));27 struct prompt *prompt = xmalloc(sizeof(*prompt));28 *prompt = (struct prompt) {28 .prompt = c32dup(prompt_text),29 .placeholder = c32dup(placeholder),30 .text = have_initial_text ? c32dup(text) : calloc(1, sizeof(char32_t)),29 .prompt = xc32dup(prompt_text),30 .placeholder = xc32dup(placeholder),31 .text = have_initial_text ? xc32dup(text) : xcalloc(1, sizeof(char32_t)),32 .cursor = have_initial_text ? c32len(text) : 0,33 };3435 return prompt;
10 unmodified lines
46 free(prompt->text);47 free(prompt);48}4949bool50void51prompt_insert_chars(struct prompt *prompt, const char *text, size_t len)52{53 size_t wlen = mbsntoc32(NULL, text, len, 0);5455 const size_t new_len = c32len(prompt->text) + wlen + 1;55 char32_t *new_text = reallocarray(prompt->text, new_len, sizeof(char32_t));56 if (new_text == NULL)57 return false;56 char32_t *new_text = xreallocarray(prompt->text, new_len, sizeof(char32_t));5758 memmove(&new_text[prompt->cursor + wlen],59 &new_text[prompt->cursor],60 (c32len(new_text) - prompt->cursor + 1) * sizeof(char32_t));
1 unmodified line
62 mbsntoc32(&new_text[prompt->cursor], text, len, wlen + 1);6364 prompt->text = new_text;65 prompt->cursor += wlen;67 return true;66}6768const char32_t *69prompt_prompt(const struct prompt *prompt)
138 unmodified lines
208bool209prompt_erase_all(struct prompt *prompt)210{211 free(prompt->text);214 prompt->text = calloc(1, sizeof(char32_t));212 prompt->text = xcalloc(1, sizeof(char32_t));213 prompt->cursor = 0;214 return true;215}216
73 unmodified lines
modified:prompt.h+1 added-1 removed
9 unmodified lines
10 const char32_t *prompt_text, const char32_t *placeholder,11 const char32_t *text);12void prompt_destroy(struct prompt *prompt);1314bool prompt_insert_chars(struct prompt *prompt, const char *text, size_t len);14void prompt_insert_chars(struct prompt *prompt, const char *text, size_t len);1516const char32_t *prompt_prompt(const struct prompt *prompt);17const char32_t *prompt_placeholder(const struct prompt *prompt);18const char32_t *prompt_text(const struct prompt *prompt);
16 unmodified lines
modified:render.c+19 added-34 removed
33 unmodified lines
34#include "log.h"35#include "char32.h"36#include "icon.h"37#include "stride.h"38#include "xmalloc.h"39#include "xsnprintf.h"4041#define min(x, y) ((x) < (y) ? (x) : (y))42#define max(x, y) ((x) > (y) ? (x) : (y))43
239 unmodified lines
283 size_t total_count = matches_get_application_visible_count(matches);284 size_t match_count = matches_get_total_count(matches);285 const char32_t *ptext = prompt_text(prompt);286285 char *text = NULL;286 int chars = asprintf(287 &text, "%zu/%zu",288 ptext[0] == U'\0' ? total_count : match_count, total_count);287 char text[64];288 size_t count = (ptext[0] == U'\0') ? total_count : match_count;289 size_t chars = xsnprintf(text, sizeof(text), "%zu/%zu", count, total_count);290290 if (chars < 0)291 return 0;292291 /* fcft wants UTF-32. Since we only use ASCII... */294 uint32_t *wtext = malloc(chars * sizeof(wtext[0]));292 uint32_t wtext[64];293 for (size_t i = 0; i < chars; i++)294 wtext[i] = (uint32_t)(unsigned char)text[i];295296 int width = -1;299 int x = buf->width - render->border_size - render->x_margin;297 int x = buf->width - render->border_size - render->x_margin;298 int y = render->border_size + render->y_margin +299 (render->row_height + font->height) / 2 - font->descent;300301 if (fcft_capabilities() & FCFT_CAPABILITY_TEXT_RUN_SHAPING) {
15 unmodified lines
317 x += glyph->advance.x;318 }319320 fcft_text_run_destroy(run);323 free(text);324 free(wtext);321 return width;322 }323 }324329 const struct fcft_glyph **glyphs = malloc(chars * sizeof(glyphs[0]));330 long *x_kern = malloc(chars * sizeof(x_kern[0]));325 const struct fcft_glyph **glyphs = xmalloc(chars * sizeof(glyphs[0]));326 long *x_kern = xmalloc(chars * sizeof(x_kern[0]));327 char32_t prev = 0;328329 width = 0;330 for (size_t i = 0; i < (size_t)chars; i++) {
28 unmodified lines
359 }360361 free(x_kern);362 free(glyphs);367 free(text);368 free(wtext);363 return width;364}365366static void
240 unmodified lines
607 clusters = (*run)->cluster;608 count = (*run)->count;609 } else {610 count = c32len(text);617 glyphs = malloc(count * sizeof(glyphs[0]));618 clusters = malloc(count * sizeof(clusters[0]));619 kern = malloc(count * sizeof(kern[0]));611 glyphs = xmalloc(count * sizeof(glyphs[0]));612 clusters = xmalloc(count * sizeof(clusters[0]));613 kern = xmalloc(count * sizeof(kern[0]));614615 for (size_t i = 0; i < count; i++) {616 const struct fcft_glyph *glyph = fcft_rasterize_char_utf32(617 font, text[i], subpixel);
141 unmodified lines
759 return;760761 float scale = svg->width > svg->height ? size / svg->width : size / svg->height;762769 uint8_t *data = malloc(size * size * 4);763 uint8_t *data = xmalloc(size * size * 4);764 nsvgRasterize(rast, svg, 0, 0, scale, data, size, size, size * 4);765766 img = pixman_image_create_bits_no_clear(767 PIXMAN_a8b8g8r8, size, size, (uint32_t *)data, size * 4);
113 unmodified lines
881 width *= scale;882 height *= scale;883884 int stride = stride_for_format_and_width(fmt, width);891 uint8_t *data = malloc(height * stride);885 uint8_t *data = xmalloc(height * stride);886 pixman_image_t *scaled_png = pixman_image_create_bits_no_clear(887 fmt, width, height, (uint32_t *)data, stride);888 pixman_image_composite32(889 PIXMAN_OP_SRC, png, NULL, scaled_png, 0, 0, 0, 0, 0, 0, width, height);
157 unmodified lines
1047 if (match->application->render_title == NULL) {1048 char32_t *newline = c32chr(match->application->title, U'\n');10491050 if (newline != NULL) {1057 char32_t *render_title = c32dup(match->application->title);1051 char32_t *render_title = xc32dup(match->application->title);10521053 newline = render_title + (newline - match->application->title);1054 *newline = U' ';1055
166 unmodified lines
12221223struct render *1224render_init(const struct config *conf, mtx_t *icon_lock)1225{1232 struct render *render = calloc(1, sizeof(*render));1226 struct render *render = xcalloc(1, sizeof(*render));1227 *render = (struct render){1228 .conf = conf,1229 .icon_lock = icon_lock,1230 };
22 unmodified lines
1253 LOG_ERR("failed to instantiate render worker mutex: %d", err);1254 goto err_free_semaphores;1255 }12561263 render->workers.threads = calloc(render->conf->render_worker_count,1264 sizeof(render->workers.threads[0]));1265 if (render->workers.threads == NULL) {1266 LOG_ERRNO("failed to allocate render worker threads array");1267 goto err_free_semaphores_and_lock;1268 }1257 render->workers.threads = xcalloc(render->conf->render_worker_count,1258 sizeof(render->workers.threads[0]));12591260 for (size_t i = 0; i < render->conf->render_worker_count; i++) {1271 struct thread_context *ctx = malloc(sizeof(*ctx));1272 if (ctx == NULL) {1273 LOG_ERRNO("failed to allocate render worker thread context");1274 goto err_free_semaphores_and_lock;1275 }12761261 struct thread_context *ctx = xmalloc(sizeof(*ctx));1262 *ctx = (struct thread_context){1263 .render = render,1264 .my_id = 1 + i,1265 };
188 unmodified lines
modified:shm.c+8 added-12 removed
19 unmodified lines
20#define LOG_ENABLE_DBG 021#include "log.h"22#include "debug.h"23#include "macros.h"24#include "xmalloc.h"2526#if !defined(MAP_UNINITIALIZED)27 #define MAP_UNINITIALIZED 028#endif
240 unmodified lines
269 const struct buffer_pool *pool = buf->pool;270271 void *mmapped = MAP_FAILED;272 struct wl_buffer *wl_buf = NULL;272 pixman_image_t **pix = calloc(buf->public.pix_instances, sizeof(pix[0]));273 pixman_image_t **pix = xcalloc(buf->public.pix_instances, sizeof(pix[0]));274275#if defined(FUZZEL_ENABLE_CAIRO)275 cairo_t **cairos = calloc(buf->public.pix_instances, sizeof(cairos[0]));276 cairo_t **cairos = xcalloc(buf->public.pix_instances, sizeof(cairos[0]));277 cairo_surface_t **cairo_surfs =277 calloc(buf->public.pix_instances, sizeof(cairo_surfs[0]));278 xcalloc(buf->public.pix_instances, sizeof(cairo_surfs[0]));279#endif280281 mmapped = (uint8_t *)pool->real_mmapped + new_offset;282
226 unmodified lines
509 LOG_ERR("failed to create SHM pool");510 goto err;511 }512512 pool = malloc(sizeof(*pool));513 if (pool == NULL) {514 LOG_ERRNO("failed to allocate buffer pool");515 goto err;516 }517513 pool = xmalloc(sizeof(*pool));514 *pool = (struct buffer_pool){515 .fd = pool_fd,516 .wl_pool = wl_pool,517 .real_mmapped = real_mmapped,
7 unmodified lines
525 continue;526 }527528 /* Push to list of available buffers, but marked as 'busy' */533 struct buffer_private *buf = malloc(sizeof(*buf));529 struct buffer_private *buf = xmalloc(sizeof(*buf));530 *buf = (struct buffer_private){531 .public = {532 .width = widths[i],533 .height = heights[i],
20 unmodified lines
554 tll_push_front(deferred, buf);555 else556 tll_push_front(chain->bufs, buf);557562 buf->public.dirty = malloc(558 buf->public.dirty = xmalloc(559 chain->pix_instances * sizeof(buf->public.dirty[0]));560561 for (size_t j = 0; j < chain->pix_instances; j++)562 pixman_region32_init(&buf->public.dirty[j]);
458 unmodified lines
10211022struct buffer_chain *1023shm_chain_new(struct wl_shm *shm, bool scrollable, size_t pix_instances)1024{1029 struct buffer_chain *chain = malloc(sizeof(*chain));1025 struct buffer_chain *chain = xmalloc(sizeof(*chain));1026 *chain = (struct buffer_chain){1027 .bufs = tll_init(),1028 .shm = shm,1029 .pix_instances = pix_instances,
20 unmodified lines
modified:uri.c+11 added-9 removed
7 unmodified lines
8#define LOG_MODULE "uri"9#define LOG_ENABLE_DBG 010#include "log.h"11#include "debug.h"12#include "macros.h"13#include "xmalloc.h"1415enum {16 HEX_DIGIT_INVALID = 1617};
43 unmodified lines
61 if (scheme_len == 0)62 goto err;6364 if (scheme != NULL)63 *scheme = strndup(start, scheme_len);65 *scheme = xstrndup(start, scheme_len);6667 LOG_DBG("scheme: \"%.*s\"", (int)scheme_len, start);6869 start = end + 1;
26 unmodified lines
96 if (user_len == 0)97 goto err;9899 if (user != NULL)98 *user = strndup(start, user_len);100 *user = xstrndup(start, user_len);101102 const char *pw = user_end + 1;103 size_t pw_len = user_pw_end - pw;104 if (pw_len == 0)105 goto err;106107 if (password != NULL)106 *password = strndup(pw, pw_len);108 *password = xstrndup(pw, pw_len);109110 LOG_DBG("user: \"%.*s\"", (int)user_len, start);111 LOG_DBG("password: \"%.*s\"", (int)pw_len, pw);112 } else {
1 unmodified line
114 if (user_len == 0)115 goto err;116117 if (user != NULL)116 *user = strndup(start, user_len);118 *user = xstrndup(start, user_len);119120 LOG_DBG("user: \"%.*s\"", (int)user_len, start);121 }122
5 unmodified lines
128 const char *host_end = memchr(start, ':', auth_left);129 if (host_end != NULL) {130 size_t host_len = host_end - start;131 if (host != NULL)130 *host = strndup(start, host_len);132 *host = xstrndup(start, host_len);133134 const char *port_str = host_end + 1;135 size_t port_len = path_segment - port_str;136 if (port_len == 0)
15 unmodified lines
152 LOG_DBG("port: \"%.*s\" (%hu)", (int)port_len, port_str, _port);153 } else {154 size_t host_len = path_segment - start;155 if (host != NULL)154 *host = strndup(start, host_len);156 *host = xstrndup(start, host_len);157158 LOG_DBG("host: \"%.*s\"", (int)host_len, start);159 }160
15 unmodified lines
176177 /* Path - decode %xx encoded characters */178 if (path != NULL) {179 const char *encoded = start;178 char *decoded = malloc(path_len + 1);180 char *decoded = xmalloc(path_len + 1);181 char *p = decoded;182183 size_t encoded_len = path_len;184 size_t UNUSED decoded_len = 0;
47 unmodified lines
232 if (query_len == 0)233 goto err;234235 if (query != NULL)234 *query = strndup(start, query_len);236 *query = xstrndup(start, query_len);237238 LOG_DBG("query: \"%.*s\"", (int)query_len, start);239240 start = fragment_start != NULL ? fragment_start + 1 : uri + len;
4 unmodified lines
245 if (left == 0)246 goto err;247248 if (fragment != NULL)247 *fragment = strndup(start, left);249 *fragment = xstrndup(start, left);250251 LOG_DBG("fragment: \"%.*s\"", (int)left, start);252 }253
25 unmodified lines
modified:wayland.c+24 added-32 removed
40 unmodified lines
41#include "key-binding.h"42#include "prompt.h"43#include "render.h"44#include "shm.h"45#include "xmalloc.h"46#include "xsnprintf.h"4748#define min(x, y) ((x) < (y) ? (x) : (y))4950struct font_spec {
439 unmodified lines
490token_done(void *data, struct xdg_activation_token_v1 *token,491 const char *name)492{493 char **xdg_activation_token = data;492 *xdg_activation_token = strdup(name);494 *xdg_activation_token = xstrdup(name);495}496497static const struct xdg_activation_token_v1_listener token_listener = {498 .done = token_done
154 unmodified lines
653654 if (wayl->conf->dmenu.enabled) {655 char *chars = ac32tombs(match->application->title);656 if (chars != NULL) {655 *refresh = prompt_insert_chars(656 wayl->prompt, chars, strlen(chars));657 prompt_insert_chars(wayl->prompt, chars, strlen(chars));658 *refresh = true;659 free(chars);660 }661 } else if (match->application->exec != NULL) {660 *refresh = prompt_insert_chars(661 wayl->prompt,662 match->application->exec,663 strlen(match->application->exec));662 const char *chars = match->application->exec;663 prompt_insert_chars(wayl->prompt, chars, strlen(chars));664 *refresh = true;665 }666667 if (*refresh)668 matches_update(wayl->matches);
310 unmodified lines
979980 if (count == 0)981 return;982982 if (!prompt_insert_chars(wayl->prompt, buf, count))983 return;983 prompt_insert_chars(wayl->prompt, buf, count);984985 matches_update_incremental(wayl->matches);986 wayl_refresh(wayl);987
281 unmodified lines
1269seat_handle_name(void *data, struct wl_seat *wl_seat, const char *name)1270{1271 struct seat *seat = data;1272 free(seat->name);1273 seat->name = strdup(name);1273 seat->name = xstrdup(name);1274}12751276static const struct wl_seat_listener seat_listener = {1277 .capabilities = seat_handle_capabilities,
79 unmodified lines
13571358 wayl->font_is_sized_by_dpi = will_size_using_dpi;13591360 if (need_font_reload) {1361 char **names = malloc(wayl->font_count * sizeof(names[0]));1361 char **names = xmalloc(wayl->font_count * sizeof(names[0]));13621363 /* Apply font size, possibly scaled using the scaling factor */1364 for (size_t i = 0; i < wayl->font_count; i++) {1365 const struct font_spec *spec = &wayl->fonts[i];1366 const bool use_px_size = spec->px_size > 0;1367 const float scale = wayl->font_is_sized_by_dpi ? 1. : new_scale;13681369 char size[64];1370 size_t size_len;1368 if (use_px_size) {1372 size_len = snprintf(1373 size, sizeof(size), ":pixelsize=%d", (int)roundf(spec->px_size * scale));1369 int px = (int)roundf(spec->px_size * scale);1370 names[i] = xasprintf("%s:pixelsize=%d", spec->pattern, px);1371 } else {1375 size_len = snprintf(1376 size, sizeof(size), ":size=%.2f", spec->pt_size * scale);1372 double pt = spec->pt_size * scale;1373 names[i] = xasprintf("%s:size=%.2f", spec->pattern, pt);1374 }13781379 size_t len = strlen(spec->pattern) + size_len + 1;1380 names[i] = malloc(len);13811382 strcpy(names[i], spec->pattern);1383 strcat(names[i], size);1375 }13761377 /* Font’s DPI */1378 float dpi = will_size_using_dpi ? new_dpi : 96.;1388 char attrs[256]; snprintf(attrs, sizeof(attrs), "dpi=%.2f", dpi);1379 char attrs[256];1380 xsnprintf(attrs, sizeof(attrs), "dpi=%.2f", dpi);13811382 char bold_attrs[512];1383 strcpy(bold_attrs, attrs);1384
134 unmodified lines
15191520 mon->dim.mm.width = physical_width;1521 mon->dim.mm.height = physical_height;1522 mon->inch = sqrt(pow(mon->dim.mm.width, 2) + pow(mon->dim.mm.height, 2)) * 0.03937008;1531 mon->make = make != NULL ? strdup(make) : NULL;1532 mon->model = model != NULL ? strdup(model) : NULL;1523 mon->make = make != NULL ? xstrdup(make) : NULL;1524 mon->model = model != NULL ? xstrdup(model) : NULL;1525 mon->subpixel = subpixel;1526 mon->transform = transform;15271528 output_update_ppi(mon);
73 unmodified lines
1602 struct monitor *mon = data;1603 struct wayland *wayl = mon->wayl;16041605 free(mon->name);1614 mon->name = name != NULL ? strdup(name) : NULL;1606 mon->name = name != NULL ? xstrdup(name) : NULL;16071608 if (wayl->conf->output != NULL &&1609 mon->name != NULL &&1610 strcmp(wayl->conf->output, mon->name) == 0)
7 unmodified lines
1618 const char *description)1619{1620 struct monitor *mon = data;1621 free(mon->description);1630 mon->description = description != NULL ? strdup(description) : NULL;1622 mon->description = description != NULL ? xstrdup(description) : NULL;1623}16241625static struct zxdg_output_v1_listener xdg_output_listener = {1626 .logical_position = xdg_output_handle_logical_position,
663 unmodified lines
2290parse_font_spec(const char *font_spec, size_t *count, struct font_spec **specs)2291{2292 tll(struct font_spec) fonts = tll_init();22932302 char *copy = strdup(font_spec);2294 char *copy = xstrdup(font_spec);2295 for (char *font = strtok(copy, ",");2296 font != NULL;2297 font = strtok(NULL, ","))2298 {
13 unmodified lines
2312 }2313 free(copy);23142315 *count = tll_length(fonts);2324 *specs = malloc(*count * sizeof((*specs)[0]));2316 *specs = xmalloc(*count * sizeof((*specs)[0]));23172318 struct font_spec *s = *specs;2319 tll_foreach(fonts, it) {2320 *s = it->item;
7 unmodified lines
2328 struct kb_manager *kb_manager,2329 struct render *render, struct prompt *prompt,2330 struct matches *matches, font_reloaded_t font_reloaded_cb, void *data)2331{2340 struct wayland *wayl = malloc(sizeof(*wayl));2332 struct wayland *wayl = xmalloc(sizeof(*wayl));2333 *wayl = (struct wayland){2334 .conf = conf,2335 .fdm = fdm,2336 .kb_manager = kb_manager,
234 unmodified lines
modified:xdg.c+35 added-55 removed
19 unmodified lines
20#define LOG_ENABLE_DBG 021#include "log.h"22#include "char32.h"23#include "icon.h"24#include "macros.h"25#include "xmalloc.h"26#include "xsnprintf.h"2728typedef tll(struct application *) application_llist_t;2930struct locale_variants {
133 unmodified lines
164 action = &tll_back(actions);165166 action->generic_name =167 default_action->generic_name != NULL165 ? c32dup(default_action->generic_name) : NULL;168 ? xc32dup(default_action->generic_name) : NULL;169 action->comment = default_action->comment != NULL167 ? c32dup(default_action->comment) : NULL;170 ? xc32dup(default_action->comment) : NULL;171 action->path = default_action->path != NULL169 ? strdup(default_action->path) : NULL;172 ? xstrdup(default_action->path) : NULL;173 action->icon = default_action->icon != NULL171 ? strdup(default_action->icon) : NULL;174 ? xstrdup(default_action->icon) : NULL;175 action->visible = default_action->visible;176 action->use_terminal = default_action->use_terminal;177178 tll_foreach(default_action->keywords, it)176 tll_push_back(action->keywords, c32dup(it->item));179 tll_push_back(action->keywords, xc32dup(it->item));180 tll_foreach(default_action->categories, it)178 tll_push_back(action->categories, c32dup(it->item));181 tll_push_back(action->categories, xc32dup(it->item));182183 action_is_valid = true;184 break;185 }
74 unmodified lines
260261 else if (strcmp(key, "Exec") == 0) {262 free(action->exec);263 free(action->wexec);261 action->exec = strdup(value);264 action->exec = xstrdup(value);265 action->wexec = ambstoc32(value);266 }267268 else if (strcmp(key, "Path") == 0) {269 free(action->path);267 action->path = strdup(value);270 action->path = xstrdup(value);271 }272273 else if (strcmp(key, "GenericName") == 0) {274 if (locale_score > action->generic_name_locale_score) {
9 unmodified lines
284 }285286 else if (strcmp(key, "StartupWMClass") == 0) {287 free(action->app_id);285 action->app_id = strdup(value);288 action->app_id = xstrdup(value);289 }290291 else if (strcmp(key, "Comment") == 0) {292 if (locale_score > action->comment_locale_score) {
37 unmodified lines
330 for (const char *action = strtok_r(value, ";", &ctx);331 action != NULL;332 action = strtok_r(NULL, ";", &ctx))333 {331 tll_push_back(action_names, strdup(action));334 tll_push_back(action_names, xstrdup(action));335 }336 }337338 else if (strcmp(key, "OnlyShowIn") == 0) {339 for (const char *desktop = strtok_r(value, ";", &ctx);340 desktop != NULL;341 desktop = strtok_r(NULL, ";", &ctx))342 {340 tll_push_back(action->onlyshowin, strdup(desktop));343 tll_push_back(action->onlyshowin, xstrdup(desktop));344 }345 }346347 else if (strcmp(key, "NotShowIn") == 0) {348 for (const char *desktop = strtok_r(value, ";", &ctx);349 desktop != NULL;350 desktop = strtok_r(NULL, ";", &ctx))351 {349 tll_push_back(action->notshowin, strdup(desktop));352 tll_push_back(action->notshowin, xstrdup(desktop));353 }354 }355356 else if (strcmp(key, "Icon") == 0) {357 free(action->icon);355 action->icon = strdup(value);358 action->icon = xstrdup(value);359 }360361 else if (strcmp(key, "Hidden") == 0 ||362 strcmp(key, "NoDisplay") == 0)
36 unmodified lines
399 if (a->name == NULL)400 a->name = ambstoc32("<no title>");401402 if (a->use_terminal && terminal != NULL && a->exec != NULL) {400 char *exec_with_terminal = malloc(401 strlen(terminal) + 1 + strlen(a->exec) + 1);402 strcpy(exec_with_terminal, terminal);403 strcat(exec_with_terminal, " ");404 strcat(exec_with_terminal, a->exec);403 char *exec_with_terminal = xstrjoin3(terminal, " ", a->exec);404 free(a->exec);405 a->exec = exec_with_terminal;406 }407408 char32_t *title = a->name;409 if (a != default_action) {411 size_t title_len = c32len(default_action->name) +412 3 + /* “ — ” */413 c32len(a->name) +414 1;415 title = malloc(title_len * sizeof(char32_t));416417 c32cpy(title, default_action->name);418 c32cat(title, U" — ");419 c32cat(title, a->name);410 title = xc32join3(default_action->name, U" — ", a->name);411 free(a->name);412 }413414 const size_t title_len = c32len(title);
9 unmodified lines
424 const size_t comment_len = action->comment != NULL425 ? c32len(action->comment)426 : 0;427437 char32_t *title_lowercase = c32dup(title);428 char32_t *title_lowercase = xc32dup(title);429 for (size_t i = 0; i < title_len; i++)430 title_lowercase[i] = toc32lower(title_lowercase[i]);431432 for (size_t i = 0; i < wexec_len; i++)
10 unmodified lines
443 for (size_t i = 0; i < c32len(it->item); i++)444 it->item[i] = toc32lower(it->item[i]);445 }446456 struct application *app = malloc(sizeof(*app));447 struct application *app = xmalloc(sizeof(*app));448 *app = (struct application){458 .id = strdup(id),449 .id = xstrdup(id),450 .index = 0, /* Not used in application mode */451 .path = a->path,452 .exec = a->exec,453 .app_id = a->app_id,454 .title = title,455 .title_lowercase = title_lowercase,465 .basename = c32dup(file_basename_lowercase),456 .basename = xc32dup(file_basename_lowercase),457 .wexec = a->wexec,458 .generic_name = a->generic_name,459 .comment = a->comment,460 .keywords = a->keywords,
21 unmodified lines
482static char *483new_id(const char *base_id, const char *new_part)484{485 if (base_id == NULL)495 return strdup(new_part);486 return xstrdup(new_part);487497 size_t len = strlen(base_id) + 1 + strlen(new_part) + 1;498 char *id = malloc(len);499500 strcpy(id, base_id);501 strcat(id, "-");502 strcat(id, new_part);503504 return id;488 return xstrjoin3(base_id, "-", new_part);489}490491static void492scan_dir(int base_fd, const char *terminal, bool include_actions,
9 unmodified lines
502 const char *locale = setlocale(LC_MESSAGES, NULL);503 struct locale_variants lc_messages = {NULL};504505 if (locale != NULL) {522 char *copy = strdup(locale);506 char *copy = xstrdup(locale);507508 char *lang = copy;509 char *country_start = strchr(copy, '_');510 char *encoding_start = strchr(copy, '.');
156 unmodified lines
667 }668669 mtx_lock(&applications->lock);670 applications->count = tll_length(apps);687 applications->v = malloc(tll_length(apps) * sizeof(applications->v[0]));671 applications->v = xmalloc(tll_length(apps) * sizeof(applications->v[0]));672673 size_t i = 0;674 tll_foreach(apps, it) {675 applications->v[i++] = it->item;
18 unmodified lines
694695 int idx = 0;696 tll_foreach(app->keywords, it) {697 idx += swprintf(&keywords[idx],714 (sizeof(keywords) / sizeof(keywords[0])) - idx,698 ALEN(keywords) - idx,699 L"%ls, ", (const wchar_t *)it->item);700 }701702 if (idx > 0)
1 unmodified line
704705 idx = 0;706 tll_foreach(app->categories, it) {707 idx += swprintf(&categories[idx],724 (sizeof(categories) / sizeof(categories[0])) - idx,708 ALEN(categories) - idx,709 L"%ls, ", (const wchar_t *)it->item);710 }711712 if (idx > 0)
34 unmodified lines
747 const char *xdg_data_home = getenv("XDG_DATA_HOME");748 if (xdg_data_home != NULL && xdg_data_home[0] != '\0') {749 int fd = open(xdg_data_home, O_RDONLY | O_DIRECTORY);750 if (fd >= 0) {767 struct xdg_data_dir d = {.fd = fd, .path = strdup(xdg_data_home)};751 struct xdg_data_dir d = {.fd = fd, .path = xstrdup(xdg_data_home)};752 tll_push_back(ret, d);753 }754 } else {771 static const char *const local = ".local/share";755 const struct passwd *pw = getpwuid(getuid());773774 char *path = malloc(strlen(pw->pw_dir) + 1 + strlen(local) + 1);775 sprintf(path, "%s/%s", pw->pw_dir, local);776756 char *path = xstrjoin(pw->pw_dir, "/.local/share");757 int fd = open(path, O_RDONLY | O_DIRECTORY);758 if (fd >= 0) {759 struct xdg_data_dir d = {.fd = fd, .path = path};760 tll_push_back(ret, d);
5 unmodified lines
766767 if (_xdg_data_dirs != NULL) {768769 char *ctx = NULL;790 char *copy = strdup(_xdg_data_dirs);770 char *copy = xstrdup(_xdg_data_dirs);771772 for (const char *tok = strtok_r(copy, ":", &ctx);773 tok != NULL;774 tok = strtok_r(NULL, ":", &ctx))775 {776 int fd = open(tok, O_RDONLY | O_DIRECTORY);777 if (fd >= 0) {798 struct xdg_data_dir d = {.fd = fd, .path = strdup(tok)};778 struct xdg_data_dir d = {.fd = fd, .path = xstrdup(tok)};779 tll_push_back(ret, d);780 }781 }782
2 unmodified lines
785 int fd1 = open("/usr/local/share", O_RDONLY | O_DIRECTORY);786 int fd2 = open("/usr/share", O_RDONLY | O_DIRECTORY);787788 if (fd1 >= 0) {809 struct xdg_data_dir d = {.fd = fd1, .path = strdup("/usr/local/share")};789 struct xdg_data_dir d = {.fd = fd1, .path = xstrdup("/usr/local/share")};790 tll_push_back(ret, d);791 }792793 if (fd2 >= 0) {814 struct xdg_data_dir d = {.fd = fd2, .path = strdup("/usr/share")};794 struct xdg_data_dir d = {.fd = fd2, .path = xstrdup("/usr/share")};795 tll_push_back(ret, d);;796 }797 }798
19 unmodified lines
818819 const char *home = getenv("HOME");820 if (home != NULL && home[0] != '\0') {821 static char path[PATH_MAX];842 snprintf(path, sizeof(path), "%s/.cache", home);822 xsnprintf(path, sizeof(path), "%s/.cache", home);823 return path;824 }825826 return NULL;
1 unmodified line
added:xmalloc.c+90 added
1#include <errno.h>2#include <limits.h>3#include <stdio.h>4#include <stdlib.h>5#include "xmalloc.h"6#include "debug.h"7#include "xsnprintf.h"89static void *10check_alloc(void *alloc)11{12 if (unlikely(alloc == NULL)) {13 FATAL_ERROR(__func__, ENOMEM);14 }15 return alloc;16}1718void *19xmalloc(size_t size)20{21 xassert(size != 0);22 return check_alloc(malloc(size));23}2425void *26xcalloc(size_t nmemb, size_t size)27{28 xassert(size != 0);29 return check_alloc(calloc(likely(nmemb) ? nmemb : 1, size));30}3132void *33xrealloc(void *ptr, size_t size)34{35 xassert(size != 0);36 return check_alloc(realloc(ptr, size));37}3839void *40xreallocarray(void *ptr, size_t nmemb, size_t size)41{42 xassert(nmemb != 0 && size != 0);43 return check_alloc(reallocarray(ptr, nmemb, size));44}4546char *47xstrdup(const char *str)48{49 return check_alloc(strdup(str));50}5152char *53xstrndup(const char *str, size_t n)54{55 return check_alloc(strndup(str, n));56}5758char32_t *59xc32dup(const char32_t *str)60{61 return check_alloc(c32dup(str));62}6364static VPRINTF(1) XMALLOC char *65xvasprintf(const char *format, va_list ap)66{67 va_list ap2;68 va_copy(ap2, ap);69 int n = vsnprintf(NULL, 0, format, ap2);70 va_end(ap2);7172 if (unlikely(n < 0 || n == INT_MAX)) {73 FATAL_ERROR(__func__, n < 0 ? errno : EOVERFLOW);74 }7576 char *str = xmalloc(n + 1);77 size_t m = xvsnprintf(str, n + 1, format, ap);78 xassert(m == n);79 return str;80}8182char *83xasprintf(const char *format, ...)84{85 va_list ap;86 va_start(ap, format);87 char *str = xvasprintf(format, ap);88 va_end(ap);89 return str;90}
added:xmalloc.h+62 added
1#pragma once23#include <stdarg.h>4#include <stddef.h>5#include <string.h>6#include <wchar.h>7#include <uchar.h>89#include "char32.h"10#include "macros.h"1112void *xmalloc(size_t size) XMALLOC;13void *xcalloc(size_t nmemb, size_t size) XMALLOC;14void *xrealloc(void *ptr, size_t size);15void *xreallocarray(void *ptr, size_t nmemb, size_t size) RETURNS_NONNULL WARN_UNUSED_RESULT;16char *xstrdup(const char *str) XSTRDUP;17char *xstrndup(const char *str, size_t n) XSTRDUP;18char32_t *xc32dup(const char32_t *str) XSTRDUP;19char *xasprintf(const char *format, ...) PRINTF(1) XMALLOC;2021static inline void *22xmemdup(const void *ptr, size_t size)23{24 return memcpy(xmalloc(size), ptr, size);25}2627static inline char *28xstrjoin(const char *s1, const char *s2)29{30 size_t n1 = strlen(s1);31 size_t n2 = strlen(s2);32 char *joined = xmalloc(n1 + n2 + 1);33 memcpy(joined, s1, n1);34 memcpy(joined + n1, s2, n2 + 1);35 return joined;36}3738static inline char *39xstrjoin3(const char *s1, const char *s2, const char *s3)40{41 size_t n1 = strlen(s1);42 size_t n2 = strlen(s2);43 size_t n3 = strlen(s3);44 char *joined = xmalloc(n1 + n2 + n3 + 1);45 memcpy(joined, s1, n1);46 memcpy(joined + n1, s2, n2);47 memcpy(joined + n1 + n2, s3, n3 + 1);48 return joined;49}5051static inline char32_t *52xc32join3(const char32_t *s1, const char32_t *s2, const char32_t *s3)53{54 size_t n1 = c32len(s1);55 size_t n2 = c32len(s2);56 size_t n3 = c32len(s3);57 char32_t *joined = xmalloc((n1 + n2 + n3 + 1) * sizeof(char32_t));58 c32memcpy(joined, s1, n1);59 c32memcpy(joined + n1, s2, n2);60 c32memcpy(joined + n1 + n2, s3, n3 + 1);61 return joined;62}
added:xsnprintf.c+54 added
1#include "xsnprintf.h"23#include <errno.h>4#include <limits.h>5#include <stdio.h>6#include "debug.h"78/*9 * ISO C doesn't require vsnprintf(3) to set errno on failure, but10 * POSIX does:11 *12 * "If an output error was encountered, these functions shall return13 * a negative value and set errno to indicate the error."14 *15 * The mandated errors of interest are:16 *17 * - EILSEQ: A wide-character code does not correspond to a valid character18 * - EOVERFLOW: The value of n is greater than INT_MAX19 * - EOVERFLOW: The value to be returned is greater than INT_MAX20 *21 * ISO C11 states:22 *23 * "The vsnprintf function returns the number of characters that would24 * have been written had n been sufficiently large, not counting the25 * terminating null character, or a negative value if an encoding error26 * occurred. Thus, the null-terminated output has been completely27 * written if and only if the returned value is nonnegative and less28 * than n."29 *30 * See also:31 *32 * - ISO C11 §7.21.6.12p333 * - https://pubs.opengroup.org/onlinepubs/9699919799/functions/vsnprintf.html34 * - https://pubs.opengroup.org/onlinepubs/9699919799/functions/snprintf.html35 */36size_t37xvsnprintf(char *restrict buf, size_t n, const char *restrict format, va_list ap)38{39 int len = vsnprintf(buf, n, format, ap);40 if (unlikely(len < 0 || len >= (int)n)) {41 FATAL_ERROR(__func__, (len < 0) ? errno : ENOBUFS);42 }43 return (size_t)len;44}4546size_t47xsnprintf(char *restrict buf, size_t n, const char *restrict format, ...)48{49 va_list ap;50 va_start(ap, format);51 size_t len = xvsnprintf(buf, n, format, ap);52 va_end(ap);53 return len;54}
added:xsnprintf.h+8 added
1#pragma once23#include <stdarg.h>4#include <stddef.h>5#include "macros.h"67size_t xsnprintf(char *restrict buf, size_t n, const char *restrict format, ...) PRINTF(3) NONNULL_ARGS;8size_t xvsnprintf(char *restrict buf, size_t n, const char *restrict format, va_list ap) VPRINTF(3) NONNULL_ARGS;