python / python/cpython

Thread-unsafe libc functions

未关闭
#127,081 3 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

extension-modules interpreter-core topic-free-threading type-bug
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Bug report

There are a a few non thread-safe libc functions used in Python that can be an issue for free threading, isolated subinterpreters, or sometimes even with the GIL.

In https://github.com/python/cpython/issues/126316, @vstinner fixed the use setgrent / getgrent. It's probably a good time to look for other similar issues.

clang-tidy

clang-tidy has a concurrency-mt-unsafe check that looks for "known-to-be-unsafe functions".

clang-tidy notes

Prerequisites: install clang-tidy-18 and bear.

./configure -C --with-pydebug --disable-gil

# generate compile_commands.json
bear -- make -j 

run-clang-tidy-18 -checks='-*,concurrency-mt-unsafe' -p .
Unsafe libc functions
  • localeconv(): not thread-safe, see glibc's manual. Is nl_langinfo a substitue?
  • setlocale
  • setpwent, getpwent, and endpwent in pwdmodule.c. These are similar to grpmodule.c and can likely be addressed the same way.
  • getservbyname, getservbyport, getprotobyname in Modules/socketmodule.c: use getservbyname_r, etc.? Note these thread-safety issues affect the default build because we release the GIL around the relevant calls.
  • dbm_open, dbm_close, etc. in Modules/_dbmmodule.c
  • getlogin: use getlogin_r if available?
Unfixable by us?
Safe due to our usage
  • getc_unlocked, safe because we use it within a flockfile() call.
  • mbrtowc() - safe as long as the passed in mbstate_t * is non-NULL, which is the case in CPython.
Safe in glibc

These functions are flagged by clang-tidy because they are not guaranteed to be safe by POSIX, but they are safe in glibc. It'd be nice to verify that they are safe in other libc implementations. I don't think it's worth changing them:

Other
  • exit(): apparently concurrent calls to exit() are not thread-safe, but I don't think it matters for our usages.
  • ptsname(): we already use ptsname_r(), but the static analyzer gets confused
Linked PRs
  • gh-132591
  • gh-132748
  • gh-132749
  • gh-132750
  • gh-132751
  • gh-135097
  • gh-135098
  • gh-139996

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

先查看链接的 PR,然后检查 Modules/pwdmodule.c、Modules/socketmodule.c 和 Modules/_dbmmodule.c 的 clang-tidy concurrency-mt-unsafe 结果。在使用 --disable-gil 完成配置后,运行文档中所述的 clang-tidy 命令;当每个相关的 libc 使用都已处理,或其安全性已得到论证时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, python
领域
operating-systems
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
20/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。