#malloc

Felix Palmen :freebsd: :c64:zirias@bsd.cafe
2025-04-28

Revisiting #async / #await in #POSIX C, trying to "add some #security" 🙈

Recap: Consider a classic #reactor-style service in C with a #threadpool attached to run the individual request handlers. When such a handler needs to do some I/O, it'll have to wait for its completion, and doing so is kind of straight forward by just blocking the worker thread executing the job until whatever I/O was needed completes.

Now, blocking a thread is never a great thing to do and I recently tooted about an interesting alternative I found: Make use of the (unfortunately deprecated) POSIX user context switching to enable releasing the worker thread while waiting. In a nutshell, you create a context with #makecontext that has its own private #stack, and then you can use #swapcontext to get off the thread, and later again to get back on the thread. A minor issue is: It must be the *same* thread ... so you might have to wait until it completes something else before you can resume your job. But then, that's probably okayish, you can make sure in your job scheduling to only use worker threads with awaited tasks attached when no other thread is available.

In my first implementation, I just used #malloc to create a 64kiB private stack for each thread job. That's perfectly fine if you can guarantee your job will never consume more stack space, AND it won't have any vulnerabilities allowing some attacker to mess with the stack. But in practice, especially for a library offering this async/await implementation, it's nothing but a wild #CVE generator.

So, I now improved on that:

* Allocate a much larger stack of now 2MiB. That alone makes issues at least less likely. And on a sane modern OS, we can still assume pages will only be mapped "on demand".
* Only allocate the stack directly before running the thread job, and delegate allocation to some internal "stack manager" that keeps track of all allocated stacks and reuses them, only freeing them on exit. This should avoid most of the allocation overhead.
* If MAP_ANON / MAP_ANONYMOUS is available, use #mmap for allocating the stack. That at least gives a chance to stay away from other allocations ....
* But finally, if MAP_STACK is available, use this flag! From my research, #FreeBSD, #OpenBSD and #NetBSD will for example make sure there's at least one "guard page" below a stack mapped with this flag, so a stack overflow consistently takes the SIGSEGV emergency exit 😆. #Linux knows this flag as well, but doesn't seem to implement such protection at this time ... 🤔

#C #coding

chibi-[N]ah🇫🇷 :gold_account:alex@social.nah.re
2025-04-24

Pfff, la journée commence bien.
#malloc

2025-02-21

As my #Friendica server, my-place.social, has grown to some 315 active users in just 5 months, I'm starting to hit up against #mariaDB limitations relating to the default memory manager, #MALLOC. This weekend I'm going to replace it with #jemalloc to reduce stalls, memory fragmentation issues, out-of-memory problems, and instability.

Friendica puts a lot of pressure on the database, mariaDB in this case, much more than Mastodon apparently does on PostgreSQL. My feeling is that the Mastodon developers have done much better database tuning.

But, none-the-less, the update must be done. This will be done on an Ubuntu server.

Does anyone who has changed the MariaDB or mySQL memory manager have any advice to share to keep me out of trouble?

BTW, #TCMalloc is not an option as other admins have reported crashes using it with Friendica.

2025-01-29

О механизмах безопасности OpenSSH: разбираем уязвимости 2024 года

Прошлый год интересно проходил для SSH. Весной — бэкдор в xz-utils (CVE-2024-3094), в результате эксплуатации которого были скомпрометированы системы с systemd. В июле — критически опасная уязвимость «состояния гонки» для систем на базе glibc, получившая название regreSSHion. Спустя еще неделю была опубликована схожая проблема, получившая идентификатор CVE- 2024- 6409. А в августе — еще одна, уже специфичная для FreeBSD, CVE-2024-7589. Как заявляют исследователи, успешная эксплуатация «состояний гонки» позволяет получить RCE (удаленное выполнение кода) на подверженных системах. Более того, regreSSHion — главный баг, ставящий под угрозу безопасность множества SSH-серверов с glibc. Интересно, что эксплуатация уязвимости не требует особой конфигурации сервера (проблема актуальна и для конфигурации по умолчанию). При этом публичного PoC нет до сих пор. Мы решили разобраться в вопросе: так ли страшны эти «состояния гонки», так ли критически опасны? И какие механизмы в sshd призваны не допустить эксплуатации этой уязвимости или хотя бы уменьшить ущерб в случае успешной атаки?

habr.com/ru/companies/pt/artic

#openssh #fsop #glibc #rce #seccomp #regression #состояние_гонки #freebsd #github #malloc

@AndyScott

Well, based on that argument against #Python, you can't be sure #Rust or #Go or any other language isn't capable of producing memory management bugs either.

In which case, try to pick a tool that reduces the risk, even if you can't guarantee it eliminates it entirely. I love C - but manual memory mangement should be the go-to in a very small number of problem domains these days, IMHO.

#MemoryManagement #malloc #free

2024-09-25

Any #macos programmers seeing this as new warning?

malloc: nano zone abandoned due to inability to reserve vm space.

I’ve never seen it before and recently upgraded to Sequoia. My reading of what little I find on the web is that the nano zone (Mork?!) shouldn’t be used unless environment variable MallocNanoZone=1.

Setting MallocNanoZone=0 clears the warning, disabling the nano zone, which may or may not be a good thing.

This is just hobby C programming that I’ve been doing all year, nothing changed but the OS upgrade.

#programming #malloc #c

2024-08-15
2024-08-01

How OpenBSD’s malloc helps the developer - Otto Moerbeek - EuroBSDcon 2023

toobnix.org/videos/watch/782f3

2024-07-14

[Перевод] Как malloc сломала JPGLoader в Serenity, или как выиграть в лотерее

Пару лет назад мне выпала возможность расследовать в SerenityOS интересный баг, связанный с декодированием изображений JPG, которые по какой-то причине при просмотре выглядели так, как вы видите выше. Странно, не так ли? Похоже, будто просто перепутали RGB и BGR. При этом внесение в JPGLoader.cpp следующего изменения: - const Color color { (u8)block.y[pixel_index], (u8)block.cb[pixel_index], (u8)block.cr[pixel_index] };
+ const Color color { (u8)block.cr[pixel_index], (u8)block.cb[pixel_index], (u8)block.y[pixel_index] };
context.bitmap->set_pixel(x, y, color); приводит к корректному показу картинки. Вроде бы можно считать дело закрытым! …Но нет. Возникает вопрос, почему вообще произошёл этот сбой?

habr.com/ru/companies/ruvds/ar

#ruvds_перевод #serenityos #jpgloader #с++ #unix #баги #rgb #malloc

Felix Palmen :freebsd: :c64:zirias@bsd.cafe
2024-07-09

@m455 IMHO, the only sane #error #handling for #malloc is something like this:

void *xmalloc(size_t sz)
{
void *p = malloc(sz);
if (!p) abort();
return p;
}

Rationale: On a "modern" OS, malloc never fails unless you'd exhaust address space (NOT available RAM). If it does, something in the OS broke. The reasons for this (see also "memory overcommitment") are a bit ugly, but that's where we are.

Even if you were on some special system (e.g. embedded) where malloc *does* fail on out-of-memory, you'd rarely find a sane strategy to continue doing anything meaningful in your program if it doesn't get the memory it needs, so, most of the time, just #abort is the sane choice here as well.

Ashwin Nanjappa 🐘codeyarns
2024-07-07

How malloc broke Serenity's JPGLoader, or: how to win the lottery - sin-ack's writings

I love good debugging stories like this one. 👌

sin-ack.github.io/posts/jpg-lo

2024-02-20

Почему проверять результат вызова malloc c помощью assert плохая идея

Указатель, который вернула функция malloc, необходимо проверить перед использованием. Неправильным решением будет использовать для этого макрос assert. В этой статье мы разберём, почему это является антипаттерном.

habr.com/ru/companies/pvs-stud

#malloc #assert #макросы #си #си++ #c #c++ #качество_кода #нулевые_указатели

2024-02-06

Следует ли проверять указатель на NULL перед вызовом функции free?

Короткий ответ: нет. Тем не менее, раз про это вновь и вновь спрашивают на Reddit, Stack Overflow и других сайтах, пришло время подробно разобрать эту тему. Оказывается, есть много интересного, о чём можно порассуждать.

habr.com/ru/companies/pvs-stud

#c #си #программирование #free #malloc #указатели #макросы #нулевые_указатели

Identifying Rust's collect::<Vec<_>>() memory leak footgun

inks.tedunangst.com/l/5066

Michael Connor BuchanTheFake_VIP@linuxrocks.online
2023-12-26

One thing that always annoyed me about operator new[]() in #C++ is how there's no equivilent of realloc(). Like, I totally get why allocating a single type doesn't need an operator resize() or whatever, but for an array, considering libc already provides you with a way to do this, it's always been strange to me it was never implemented. #cpp #malloc

2023-12-02

[Перевод] std fs в Rust медленнее, чем Python? Нет, это аппаратный баг

В этой статье я поделюсь с вами долгой историей, которая начинается с op.read() opendal , а заканчивается неожиданным поворотом. Это путешествие оказалось для меня достаточно поучительным, надеюсь, и для вас оно будет таким же. Я постараюсь максимально точно воссоздать свой опыт и дополню его выводами, которые сделал в процессе.

habr.com/ru/articles/778026/

#malloc #glibc #jemalloc #pymalloc #amd #аппаратные_проблемы

blake shaw 🇵🇸rml@functional.cafe
2023-10-24
Peter N. M. Hansteenpitrh
2023-10-24

Client Info

Server: https://mastodon.social
Version: 2025.04
Repository: https://github.com/cyevgeniy/lmst