id
int64 0
886
| original_context
stringlengths 648
56.6k
| modified_context
stringlengths 587
47.6k
| omitted_context
sequencelengths 0
19
| omitted_index
sequencelengths 0
19
| metadata
dict |
---|---|---|---|---|---|
700 | diff --git a/SConstruct b/SConstruct
index bcc2094f0541..8e3e06c52f2e 100644
--- a/SConstruct
+++ b/SConstruct
@@ -1156,15 +1156,6 @@ if env["vsproj"]:
env["CPPPATH"] = [Dir(path) for path in env["CPPPATH"]]
methods.generate_vs_project(env, ARGUMENTS, env["vsproj_name"])
-# Check for the existence of headers
-conf = Configure(env)
-if "check_c_headers" in env:
- headers = env["check_c_headers"]
- for header in headers:
- if conf.CheckCHeader(header):
- env.AppendUnique(CPPDEFINES=[headers[header]])
-conf.Finish()
-
# Miscellaneous & post-build methods.
if not env.GetOption("clean") and not env.GetOption("help"):
methods.dump(env)
diff --git a/drivers/unix/SCsub b/drivers/unix/SCsub
index bca4acfd7400..9ad6234fbe4b 100644
--- a/drivers/unix/SCsub
+++ b/drivers/unix/SCsub
@@ -4,5 +4,3 @@ from misc.utility.scons_hints import *
Import("env")
env.add_source_files(env.drivers_sources, "*.cpp")
-
-env["check_c_headers"] = {"mntent.h": "HAVE_MNTENT"}
diff --git a/drivers/unix/dir_access_unix.cpp b/drivers/unix/dir_access_unix.cpp
index 93491a96b146..fc63cc80cbba 100644
--- a/drivers/unix/dir_access_unix.cpp
+++ b/drivers/unix/dir_access_unix.cpp
@@ -46,7 +46,7 @@
#include <sys/stat.h>
#include <sys/statvfs.h>
-#ifdef HAVE_MNTENT
+#if __has_include(<mntent.h>)
#include <mntent.h>
#endif
@@ -192,7 +192,7 @@ void DirAccessUnix::list_dir_end() {
_cisdir = false;
}
-#if defined(HAVE_MNTENT) && defined(LINUXBSD_ENABLED)
+#if __has_include(<mntent.h>) && defined(LINUXBSD_ENABLED)
static bool _filter_drive(struct mntent *mnt) {
// Ignore devices that don't point to /dev
if (strncmp(mnt->mnt_fsname, "/dev", 4) != 0) {
@@ -216,7 +216,7 @@ static void _get_drives(List<String> *list) {
// Add root.
list->push_back("/");
-#if defined(HAVE_MNTENT) && defined(LINUXBSD_ENABLED)
+#if __has_include(<mntent.h>) && defined(LINUXBSD_ENABLED)
// Check /etc/mtab for the list of mounted partitions.
FILE *mtab = setmntent("/etc/mtab", "r");
if (mtab) {
diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp
index 62359a3bba87..002ca10439cf 100644
--- a/platform/linuxbsd/os_linuxbsd.cpp
+++ b/platform/linuxbsd/os_linuxbsd.cpp
@@ -76,7 +76,7 @@
#include <sys/utsname.h>
#include <unistd.h>
-#ifdef HAVE_MNTENT
+#if __has_include(<mntent.h>)
#include <mntent.h>
#endif
@@ -999,7 +999,7 @@ static String get_mountpoint(const String &p_path) {
return "";
}
-#ifdef HAVE_MNTENT
+#if __has_include(<mntent.h>)
dev_t dev = s.st_dev;
FILE *fd = setmntent("/proc/mounts", "r");
if (!fd) {
| diff --git a/SConstruct b/SConstruct
index bcc2094f0541..8e3e06c52f2e 100644
--- a/SConstruct
+++ b/SConstruct
@@ -1156,15 +1156,6 @@ if env["vsproj"]:
env["CPPPATH"] = [Dir(path) for path in env["CPPPATH"]]
methods.generate_vs_project(env, ARGUMENTS, env["vsproj_name"])
-# Check for the existence of headers
-conf = Configure(env)
- headers = env["check_c_headers"]
- for header in headers:
- env.AppendUnique(CPPDEFINES=[headers[header]])
-conf.Finish()
# Miscellaneous & post-build methods.
if not env.GetOption("clean") and not env.GetOption("help"):
methods.dump(env)
diff --git a/drivers/unix/SCsub b/drivers/unix/SCsub
index bca4acfd7400..9ad6234fbe4b 100644
--- a/drivers/unix/SCsub
+++ b/drivers/unix/SCsub
@@ -4,5 +4,3 @@ from misc.utility.scons_hints import *
Import("env")
env.add_source_files(env.drivers_sources, "*.cpp")
-env["check_c_headers"] = {"mntent.h": "HAVE_MNTENT"}
diff --git a/drivers/unix/dir_access_unix.cpp b/drivers/unix/dir_access_unix.cpp
index 93491a96b146..fc63cc80cbba 100644
--- a/drivers/unix/dir_access_unix.cpp
+++ b/drivers/unix/dir_access_unix.cpp
@@ -46,7 +46,7 @@
#include <sys/stat.h>
#include <sys/statvfs.h>
@@ -192,7 +192,7 @@ void DirAccessUnix::list_dir_end() {
_cisdir = false;
}
static bool _filter_drive(struct mntent *mnt) {
// Ignore devices that don't point to /dev
if (strncmp(mnt->mnt_fsname, "/dev", 4) != 0) {
@@ -216,7 +216,7 @@ static void _get_drives(List<String> *list) {
// Add root.
list->push_back("/");
// Check /etc/mtab for the list of mounted partitions.
FILE *mtab = setmntent("/etc/mtab", "r");
if (mtab) {
diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp
index 62359a3bba87..002ca10439cf 100644
--- a/platform/linuxbsd/os_linuxbsd.cpp
+++ b/platform/linuxbsd/os_linuxbsd.cpp
@@ -76,7 +76,7 @@
#include <sys/utsname.h>
#include <unistd.h>
@@ -999,7 +999,7 @@ static String get_mountpoint(const String &p_path) {
return "";
}
dev_t dev = s.st_dev;
FILE *fd = setmntent("/proc/mounts", "r");
if (!fd) { | [
"-if \"check_c_headers\" in env:",
"- if conf.CheckCHeader(header):"
] | [
10,
13
] | {
"additions": 5,
"author": "Repiteo",
"deletions": 16,
"html_url": "https://github.com/godotengine/godot/pull/103865",
"issue_id": 103865,
"merged_at": "2025-04-25T16:42:00Z",
"omission_probability": 0.1,
"pr_number": 103865,
"repo": "godotengine/godot",
"title": "SCons: Remove `check_c_headers`",
"total_changes": 21
} |
701 | diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs
index 7b6b35b68fe3..d17b7327822c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs
@@ -59,6 +59,11 @@ internal static unsafe godot_bool Set(IntPtr godotObjectGCHandle, godot_string_n
return godot_bool.True;
}
+ if (!godotObject.HasGodotClassMethod(GodotObject.MethodName._Set.NativeValue.DangerousSelfRef))
+ {
+ return godot_bool.False;
+ }
+
var nameManaged = StringName.CreateTakingOwnershipOfDisposableValue(
NativeFuncs.godotsharp_string_name_new_copy(CustomUnsafe.AsRef(name)));
@@ -107,6 +112,11 @@ internal static unsafe godot_bool Get(IntPtr godotObjectGCHandle, godot_string_n
return godot_bool.True;
}
+ if (!godotObject.HasGodotClassMethod(GodotObject.MethodName._Get.NativeValue.DangerousSelfRef))
+ {
+ return godot_bool.False;
+ }
+
var nameManaged = StringName.CreateTakingOwnershipOfDisposableValue(
NativeFuncs.godotsharp_string_name_new_copy(CustomUnsafe.AsRef(name)));
| diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs
index 7b6b35b68fe3..d17b7327822c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs
@@ -59,6 +59,11 @@ internal static unsafe godot_bool Set(IntPtr godotObjectGCHandle, godot_string_n
+ if (!godotObject.HasGodotClassMethod(GodotObject.MethodName._Set.NativeValue.DangerousSelfRef))
@@ -107,6 +112,11 @@ internal static unsafe godot_bool Get(IntPtr godotObjectGCHandle, godot_string_n
+ if (!godotObject.HasGodotClassMethod(GodotObject.MethodName._Get.NativeValue.DangerousSelfRef)) | [] | [] | {
"additions": 10,
"author": "Delsin-Yu",
"deletions": 0,
"html_url": "https://github.com/godotengine/godot/pull/104689",
"issue_id": 104689,
"merged_at": "2025-04-15T00:42:51Z",
"omission_probability": 0.1,
"pr_number": 104689,
"repo": "godotengine/godot",
"title": "[.Net] Avoid unnecessary StringName allocations on not implemented virtual `_Get` and `_Set` method call",
"total_changes": 10
} |
702 | diff --git a/doc/classes/LineEdit.xml b/doc/classes/LineEdit.xml
index 426c3bbb6080..469601f51fe8 100644
--- a/doc/classes/LineEdit.xml
+++ b/doc/classes/LineEdit.xml
@@ -133,6 +133,22 @@
[b]Warning:[/b] This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their [member Window.visible] property.
</description>
</method>
+ <method name="get_next_composite_character_column" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="column" type="int" />
+ <description>
+ Returns the correct column at the end of a composite character like ❤️🩹 (mending heart; Unicode: [code]U+2764 U+FE0F U+200D U+1FA79[/code]) which is comprised of more than one Unicode code point, if the caret is at the start of the composite character. Also returns the correct column with the caret at mid grapheme and for non-composite characters.
+ [b]Note:[/b] To check at caret location use [code]get_next_composite_character_column(get_caret_column())[/code]
+ </description>
+ </method>
+ <method name="get_previous_composite_character_column" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="column" type="int" />
+ <description>
+ Returns the correct column at the start of a composite character like ❤️🩹 (mending heart; Unicode: [code]U+2764 U+FE0F U+200D U+1FA79[/code]) which is comprised of more than one Unicode code point, if the caret is at the end of the composite character. Also returns the correct column with the caret at mid grapheme and for non-composite characters.
+ [b]Note:[/b] To check at caret location use [code]get_previous_composite_character_column(get_caret_column())[/code]
+ </description>
+ </method>
<method name="get_scroll_offset" qualifiers="const">
<return type="float" />
<description>
@@ -246,6 +262,9 @@
<member name="alignment" type="int" setter="set_horizontal_alignment" getter="get_horizontal_alignment" enum="HorizontalAlignment" default="0">
Text alignment as defined in the [enum HorizontalAlignment] enum.
</member>
+ <member name="backspace_deletes_composite_character_enabled" type="bool" setter="set_backspace_deletes_composite_character_enabled" getter="is_backspace_deletes_composite_character_enabled" default="false">
+ If [code]true[/code] and [member caret_mid_grapheme] is [code]false[/code], backspace deletes an entire composite character such as ❤️🩹, instead of deleting part of the composite character.
+ </member>
<member name="caret_blink" type="bool" setter="set_caret_blink_enabled" getter="is_caret_blink_enabled" default="false">
If [code]true[/code], makes the caret blink.
</member>
diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml
index e04a8284aff6..463cc936e937 100644
--- a/doc/classes/TextEdit.xml
+++ b/doc/classes/TextEdit.xml
@@ -517,6 +517,15 @@
Returns the number of lines that may be drawn on the minimap.
</description>
</method>
+ <method name="get_next_composite_character_column" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="line" type="int" />
+ <param index="1" name="column" type="int" />
+ <description>
+ Returns the correct column at the end of a composite character like ❤️🩹 (mending heart; Unicode: [code]U+2764 U+FE0F U+200D U+1FA79[/code]) which is comprised of more than one Unicode code point, if the caret is at the start of the composite character. Also returns the correct column with the caret at mid grapheme and for non-composite characters.
+ [b]Note:[/b] To check at caret location use [code]get_next_composite_character_column(get_caret_line(), get_caret_column())[/code]
+ </description>
+ </method>
<method name="get_next_visible_line_index_offset_from" qualifiers="const">
<return type="Vector2i" />
<param index="0" name="line" type="int" />
@@ -543,6 +552,15 @@
[b]Note:[/b] The Y position corresponds to the bottom side of the line. Use [method get_rect_at_line_column] to get the top side position.
</description>
</method>
+ <method name="get_previous_composite_character_column" qualifiers="const">
+ <return type="int" />
+ <param index="0" name="line" type="int" />
+ <param index="1" name="column" type="int" />
+ <description>
+ Returns the correct column at the start of a composite character like ❤️🩹 (mending heart; Unicode: [code]U+2764 U+FE0F U+200D U+1FA79[/code]) which is comprised of more than one Unicode code point, if the caret is at the end of the composite character. Also returns the correct column with the caret at mid grapheme and for non-composite characters.
+ [b]Note:[/b] To check at caret location use [code]get_previous_composite_character_column(get_caret_line(), get_caret_column())[/code]
+ </description>
+ </method>
<method name="get_rect_at_line_column" qualifiers="const">
<return type="Rect2i" />
<param index="0" name="line" type="int" />
@@ -1265,6 +1283,9 @@
<member name="autowrap_mode" type="int" setter="set_autowrap_mode" getter="get_autowrap_mode" enum="TextServer.AutowrapMode" default="3">
If [member wrap_mode] is set to [constant LINE_WRAPPING_BOUNDARY], sets text wrapping mode. To see how each mode behaves, see [enum TextServer.AutowrapMode].
</member>
+ <member name="backspace_deletes_composite_character_enabled" type="bool" setter="set_backspace_deletes_composite_character_enabled" getter="is_backspace_deletes_composite_character_enabled" default="false">
+ If [code]true[/code] and [member caret_mid_grapheme] is [code]false[/code], backspace deletes an entire composite character such as ❤️🩹, instead of deleting part of the composite character.
+ </member>
<member name="caret_blink" type="bool" setter="set_caret_blink_enabled" getter="is_caret_blink_enabled" default="false">
If [code]true[/code], makes the caret blink.
</member>
diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp
index a5d4cfc1f5e7..c2aaf8e67286 100644
--- a/scene/gui/code_edit.cpp
+++ b/scene/gui/code_edit.cpp
@@ -808,7 +808,14 @@ void CodeEdit::_backspace_internal(int p_caret) {
}
int from_line = to_column > 0 ? to_line : to_line - 1;
- int from_column = to_column > 0 ? (to_column - 1) : (get_line(to_line - 1).length());
+ int from_column = 0;
+ if (to_column == 0) {
+ from_column = get_line(to_line - 1).length();
+ } else if (TextEdit::is_caret_mid_grapheme_enabled() || !TextEdit::is_backspace_deletes_composite_character_enabled()) {
+ from_column = to_column - 1;
+ } else {
+ from_column = TextEdit::get_previous_composite_character_column(to_line, to_column);
+ }
merge_gutters(from_line, to_line);
diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp
index 87148d5e62d6..df53061a29d6 100644
--- a/scene/gui/line_edit.cpp
+++ b/scene/gui/line_edit.cpp
@@ -1955,11 +1955,14 @@ void LineEdit::delete_char() {
if (text.is_empty() || caret_column == 0) {
return;
}
-
- text = text.left(caret_column - 1) + text.substr(caret_column);
+ int delete_char_offset = 1;
+ if (!caret_mid_grapheme_enabled && backspace_deletes_composite_character_enabled) {
+ delete_char_offset = caret_column - get_previous_composite_character_column(caret_column);
+ }
+ text = text.left(caret_column - delete_char_offset) + text.substr(caret_column);
_shape();
- set_caret_column(get_caret_column() - 1);
+ set_caret_column(get_caret_column() - delete_char_offset);
_text_changed();
}
@@ -2213,6 +2216,24 @@ int LineEdit::get_caret_column() const {
return caret_column;
}
+int LineEdit::get_next_composite_character_column(int p_column) const {
+ ERR_FAIL_INDEX_V(p_column, text.length() + 1, -1);
+ if (p_column == text.length()) {
+ return p_column;
+ } else {
+ return TS->shaped_text_next_character_pos(text_rid, p_column);
+ }
+}
+
+int LineEdit::get_previous_composite_character_column(int p_column) const {
+ ERR_FAIL_INDEX_V(p_column, text.length() + 1, -1);
+ if (p_column == 0) {
+ return 0;
+ } else {
+ return TS->shaped_text_prev_character_pos(text_rid, p_column);
+ }
+}
+
void LineEdit::set_scroll_offset(float p_pos) {
scroll_offset = p_pos;
if (scroll_offset < 0.0) {
@@ -2629,6 +2650,14 @@ bool LineEdit::is_emoji_menu_enabled() const {
return emoji_menu_enabled;
}
+void LineEdit::set_backspace_deletes_composite_character_enabled(bool p_enabled) {
+ backspace_deletes_composite_character_enabled = p_enabled;
+}
+
+bool LineEdit::is_backspace_deletes_composite_character_enabled() const {
+ return backspace_deletes_composite_character_enabled;
+}
+
bool LineEdit::is_menu_visible() const {
return menu && menu->is_visible();
}
@@ -3092,6 +3121,8 @@ void LineEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_placeholder"), &LineEdit::get_placeholder);
ClassDB::bind_method(D_METHOD("set_caret_column", "position"), &LineEdit::set_caret_column);
ClassDB::bind_method(D_METHOD("get_caret_column"), &LineEdit::get_caret_column);
+ ClassDB::bind_method(D_METHOD("get_next_composite_character_column", "column"), &LineEdit::get_next_composite_character_column);
+ ClassDB::bind_method(D_METHOD("get_previous_composite_character_column", "column"), &LineEdit::get_previous_composite_character_column);
ClassDB::bind_method(D_METHOD("get_scroll_offset"), &LineEdit::get_scroll_offset);
ClassDB::bind_method(D_METHOD("set_expand_to_text_length_enabled", "enabled"), &LineEdit::set_expand_to_text_length_enabled);
ClassDB::bind_method(D_METHOD("is_expand_to_text_length_enabled"), &LineEdit::is_expand_to_text_length_enabled);
@@ -3124,6 +3155,8 @@ void LineEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_context_menu_enabled"), &LineEdit::is_context_menu_enabled);
ClassDB::bind_method(D_METHOD("set_emoji_menu_enabled", "enable"), &LineEdit::set_emoji_menu_enabled);
ClassDB::bind_method(D_METHOD("is_emoji_menu_enabled"), &LineEdit::is_emoji_menu_enabled);
+ ClassDB::bind_method(D_METHOD("set_backspace_deletes_composite_character_enabled", "enable"), &LineEdit::set_backspace_deletes_composite_character_enabled);
+ ClassDB::bind_method(D_METHOD("is_backspace_deletes_composite_character_enabled"), &LineEdit::is_backspace_deletes_composite_character_enabled);
ClassDB::bind_method(D_METHOD("set_virtual_keyboard_enabled", "enable"), &LineEdit::set_virtual_keyboard_enabled);
ClassDB::bind_method(D_METHOD("is_virtual_keyboard_enabled"), &LineEdit::is_virtual_keyboard_enabled);
ClassDB::bind_method(D_METHOD("set_virtual_keyboard_type", "type"), &LineEdit::set_virtual_keyboard_type);
@@ -3203,6 +3236,7 @@ void LineEdit::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "expand_to_text_length"), "set_expand_to_text_length_enabled", "is_expand_to_text_length_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "context_menu_enabled"), "set_context_menu_enabled", "is_context_menu_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emoji_menu_enabled"), "set_emoji_menu_enabled", "is_emoji_menu_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "backspace_deletes_composite_character_enabled"), "set_backspace_deletes_composite_character_enabled", "is_backspace_deletes_composite_character_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "virtual_keyboard_enabled"), "set_virtual_keyboard_enabled", "is_virtual_keyboard_enabled");
ADD_PROPERTY(PropertyInfo(Variant::INT, "virtual_keyboard_type", PROPERTY_HINT_ENUM, "Default,Multiline,Number,Decimal,Phone,Email,Password,URL"), "set_virtual_keyboard_type", "get_virtual_keyboard_type");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clear_button_enabled"), "set_clear_button_enabled", "is_clear_button_enabled");
diff --git a/scene/gui/line_edit.h b/scene/gui/line_edit.h
index 672c66cd32b5..709c64dc6ee5 100644
--- a/scene/gui/line_edit.h
+++ b/scene/gui/line_edit.h
@@ -122,6 +122,7 @@ class LineEdit : public Control {
bool context_menu_enabled = true;
bool emoji_menu_enabled = true;
+ bool backspace_deletes_composite_character_enabled = false;
PopupMenu *menu = nullptr;
PopupMenu *menu_dir = nullptr;
PopupMenu *menu_ctl = nullptr;
@@ -309,6 +310,9 @@ class LineEdit : public Control {
void set_emoji_menu_enabled(bool p_enabled);
bool is_emoji_menu_enabled() const;
+ void set_backspace_deletes_composite_character_enabled(bool p_enabled);
+ bool is_backspace_deletes_composite_character_enabled() const;
+
void select(int p_from = 0, int p_to = -1);
void select_all();
void selection_delete();
@@ -345,6 +349,8 @@ class LineEdit : public Control {
void set_caret_column(int p_column);
int get_caret_column() const;
+ int get_next_composite_character_column(int p_column) const;
+ int get_previous_composite_character_column(int p_column) const;
void set_max_length(int p_max_length);
int get_max_length() const;
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index 7e3bf4519dd6..4bc00d885788 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -3723,6 +3723,14 @@ bool TextEdit::is_emoji_menu_enabled() const {
return emoji_menu_enabled;
}
+void TextEdit::set_backspace_deletes_composite_character_enabled(bool p_enabled) {
+ backspace_deletes_composite_character_enabled = p_enabled;
+}
+
+bool TextEdit::is_backspace_deletes_composite_character_enabled() const {
+ return backspace_deletes_composite_character_enabled;
+}
+
void TextEdit::set_shortcut_keys_enabled(bool p_enabled) {
shortcut_keys_enabled = p_enabled;
}
@@ -6056,6 +6064,26 @@ int TextEdit::get_selection_origin_column(int p_caret) const {
return carets[p_caret].selection.origin_column;
}
+int TextEdit::get_next_composite_character_column(int p_line, int p_column) const {
+ ERR_FAIL_INDEX_V(p_line, text.size(), -1);
+ ERR_FAIL_INDEX_V(p_column, text[p_line].length() + 1, -1);
+ if (p_column == text[p_line].length()) {
+ return p_column;
+ } else {
+ return TS->shaped_text_next_character_pos(text.get_line_data(p_line)->get_rid(), (p_column));
+ }
+}
+
+int TextEdit::get_previous_composite_character_column(int p_line, int p_column) const {
+ ERR_FAIL_INDEX_V(p_line, text.size(), -1);
+ ERR_FAIL_INDEX_V(p_column, text[p_line].length() + 1, -1);
+ if (p_column == 0) {
+ return 0;
+ } else {
+ return TS->shaped_text_prev_character_pos(text.get_line_data(p_line)->get_rid(), p_column);
+ }
+}
+
int TextEdit::get_selection_from_line(int p_caret) const {
ERR_FAIL_INDEX_V(p_caret, carets.size(), -1);
if (!has_selection(p_caret)) {
@@ -6957,6 +6985,9 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_emoji_menu_enabled", "enable"), &TextEdit::set_emoji_menu_enabled);
ClassDB::bind_method(D_METHOD("is_emoji_menu_enabled"), &TextEdit::is_emoji_menu_enabled);
+ ClassDB::bind_method(D_METHOD("set_backspace_deletes_composite_character_enabled", "enable"), &TextEdit::set_backspace_deletes_composite_character_enabled);
+ ClassDB::bind_method(D_METHOD("is_backspace_deletes_composite_character_enabled"), &TextEdit::is_backspace_deletes_composite_character_enabled);
+
ClassDB::bind_method(D_METHOD("set_shortcut_keys_enabled", "enabled"), &TextEdit::set_shortcut_keys_enabled);
ClassDB::bind_method(D_METHOD("is_shortcut_keys_enabled"), &TextEdit::is_shortcut_keys_enabled);
@@ -7150,6 +7181,8 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_caret_column", "column", "adjust_viewport", "caret_index"), &TextEdit::set_caret_column, DEFVAL(true), DEFVAL(0));
ClassDB::bind_method(D_METHOD("get_caret_column", "caret_index"), &TextEdit::get_caret_column, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_next_composite_character_column", "line", "column"), &TextEdit::get_next_composite_character_column);
+ ClassDB::bind_method(D_METHOD("get_previous_composite_character_column", "line", "column"), &TextEdit::get_previous_composite_character_column);
ClassDB::bind_method(D_METHOD("get_caret_wrap_index", "caret_index"), &TextEdit::get_caret_wrap_index, DEFVAL(0));
@@ -7359,6 +7392,7 @@ void TextEdit::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "context_menu_enabled"), "set_context_menu_enabled", "is_context_menu_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emoji_menu_enabled"), "set_emoji_menu_enabled", "is_emoji_menu_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "backspace_deletes_composite_character_enabled"), "set_backspace_deletes_composite_character_enabled", "is_backspace_deletes_composite_character_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_keys_enabled"), "set_shortcut_keys_enabled", "is_shortcut_keys_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "selecting_enabled"), "set_selecting_enabled", "is_selecting_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "deselect_on_focus_loss_enabled"), "set_deselect_on_focus_loss_enabled", "is_deselect_on_focus_loss_enabled");
@@ -7595,7 +7629,14 @@ void TextEdit::_backspace_internal(int p_caret) {
}
int from_line = to_column > 0 ? to_line : to_line - 1;
- int from_column = to_column > 0 ? (to_column - 1) : (text[to_line - 1].length());
+ int from_column = 0;
+ if (to_column == 0) {
+ from_column = text[to_line - 1].length();
+ } else if (caret_mid_grapheme_enabled || !backspace_deletes_composite_character_enabled) {
+ from_column = to_column - 1;
+ } else {
+ from_column = get_previous_composite_character_column(to_line, to_column);
+ }
merge_gutters(from_line, to_line);
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index 8f6a5be6e7fc..e0b785e7cf14 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -340,6 +340,7 @@ class TextEdit : public Control {
bool overtype_mode = false;
bool context_menu_enabled = true;
bool emoji_menu_enabled = true;
+ bool backspace_deletes_composite_character_enabled = false;
bool shortcut_keys_enabled = true;
bool virtual_keyboard_enabled = true;
bool middle_mouse_paste_enabled = true;
@@ -813,6 +814,9 @@ class TextEdit : public Control {
void set_emoji_menu_enabled(bool p_enabled);
bool is_emoji_menu_enabled() const;
+ void set_backspace_deletes_composite_character_enabled(bool p_enabled);
+ bool is_backspace_deletes_composite_character_enabled() const;
+
void set_shortcut_keys_enabled(bool p_enabled);
bool is_shortcut_keys_enabled() const;
@@ -960,6 +964,8 @@ class TextEdit : public Control {
void set_caret_column(int p_column, bool p_adjust_viewport = true, int p_caret = 0);
int get_caret_column(int p_caret = 0) const;
+ int get_next_composite_character_column(int p_line, int p_column) const;
+ int get_previous_composite_character_column(int p_line, int p_column) const;
int get_caret_wrap_index(int p_caret = 0) const;
| diff --git a/doc/classes/LineEdit.xml b/doc/classes/LineEdit.xml
index 426c3bbb6080..469601f51fe8 100644
--- a/doc/classes/LineEdit.xml
+++ b/doc/classes/LineEdit.xml
@@ -133,6 +133,22 @@
[b]Warning:[/b] This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their [member Window.visible] property.
+ [b]Note:[/b] To check at caret location use [code]get_next_composite_character_column(get_caret_column())[/code]
+ [b]Note:[/b] To check at caret location use [code]get_previous_composite_character_column(get_caret_column())[/code]
<method name="get_scroll_offset" qualifiers="const">
<return type="float" />
<description>
@@ -246,6 +262,9 @@
<member name="alignment" type="int" setter="set_horizontal_alignment" getter="get_horizontal_alignment" enum="HorizontalAlignment" default="0">
Text alignment as defined in the [enum HorizontalAlignment] enum.
diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml
index e04a8284aff6..463cc936e937 100644
--- a/doc/classes/TextEdit.xml
+++ b/doc/classes/TextEdit.xml
@@ -517,6 +517,15 @@
Returns the number of lines that may be drawn on the minimap.
+ [b]Note:[/b] To check at caret location use [code]get_next_composite_character_column(get_caret_line(), get_caret_column())[/code]
<method name="get_next_visible_line_index_offset_from" qualifiers="const">
<return type="Vector2i" />
@@ -543,6 +552,15 @@
[b]Note:[/b] The Y position corresponds to the bottom side of the line. Use [method get_rect_at_line_column] to get the top side position.
<method name="get_rect_at_line_column" qualifiers="const">
<return type="Rect2i" />
@@ -1265,6 +1283,9 @@
<member name="autowrap_mode" type="int" setter="set_autowrap_mode" getter="get_autowrap_mode" enum="TextServer.AutowrapMode" default="3">
If [member wrap_mode] is set to [constant LINE_WRAPPING_BOUNDARY], sets text wrapping mode. To see how each mode behaves, see [enum TextServer.AutowrapMode].
diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp
index a5d4cfc1f5e7..c2aaf8e67286 100644
--- a/scene/gui/code_edit.cpp
+++ b/scene/gui/code_edit.cpp
@@ -808,7 +808,14 @@ void CodeEdit::_backspace_internal(int p_caret) {
- int from_column = to_column > 0 ? (to_column - 1) : (get_line(to_line - 1).length());
+ } else if (TextEdit::is_caret_mid_grapheme_enabled() || !TextEdit::is_backspace_deletes_composite_character_enabled()) {
+ from_column = TextEdit::get_previous_composite_character_column(to_line, to_column);
diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp
index 87148d5e62d6..df53061a29d6 100644
--- a/scene/gui/line_edit.cpp
+++ b/scene/gui/line_edit.cpp
@@ -1955,11 +1955,14 @@ void LineEdit::delete_char() {
if (text.is_empty() || caret_column == 0) {
return;
}
-
- text = text.left(caret_column - 1) + text.substr(caret_column);
+ delete_char_offset = caret_column - get_previous_composite_character_column(caret_column);
+ text = text.left(caret_column - delete_char_offset) + text.substr(caret_column);
_shape();
- set_caret_column(get_caret_column() - 1);
+ set_caret_column(get_caret_column() - delete_char_offset);
_text_changed();
@@ -2213,6 +2216,24 @@ int LineEdit::get_caret_column() const {
return caret_column;
+int LineEdit::get_next_composite_character_column(int p_column) const {
+ if (p_column == text.length()) {
+ return TS->shaped_text_next_character_pos(text_rid, p_column);
void LineEdit::set_scroll_offset(float p_pos) {
scroll_offset = p_pos;
if (scroll_offset < 0.0) {
@@ -2629,6 +2650,14 @@ bool LineEdit::is_emoji_menu_enabled() const {
+void LineEdit::set_backspace_deletes_composite_character_enabled(bool p_enabled) {
+bool LineEdit::is_backspace_deletes_composite_character_enabled() const {
bool LineEdit::is_menu_visible() const {
return menu && menu->is_visible();
@@ -3092,6 +3121,8 @@ void LineEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_placeholder"), &LineEdit::get_placeholder);
ClassDB::bind_method(D_METHOD("set_caret_column", "position"), &LineEdit::set_caret_column);
ClassDB::bind_method(D_METHOD("get_caret_column"), &LineEdit::get_caret_column);
+ ClassDB::bind_method(D_METHOD("get_next_composite_character_column", "column"), &LineEdit::get_next_composite_character_column);
+ ClassDB::bind_method(D_METHOD("get_previous_composite_character_column", "column"), &LineEdit::get_previous_composite_character_column);
ClassDB::bind_method(D_METHOD("get_scroll_offset"), &LineEdit::get_scroll_offset);
ClassDB::bind_method(D_METHOD("set_expand_to_text_length_enabled", "enabled"), &LineEdit::set_expand_to_text_length_enabled);
ClassDB::bind_method(D_METHOD("is_expand_to_text_length_enabled"), &LineEdit::is_expand_to_text_length_enabled);
@@ -3124,6 +3155,8 @@ void LineEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_context_menu_enabled"), &LineEdit::is_context_menu_enabled);
ClassDB::bind_method(D_METHOD("set_emoji_menu_enabled", "enable"), &LineEdit::set_emoji_menu_enabled);
ClassDB::bind_method(D_METHOD("is_emoji_menu_enabled"), &LineEdit::is_emoji_menu_enabled);
+ ClassDB::bind_method(D_METHOD("set_backspace_deletes_composite_character_enabled", "enable"), &LineEdit::set_backspace_deletes_composite_character_enabled);
ClassDB::bind_method(D_METHOD("set_virtual_keyboard_enabled", "enable"), &LineEdit::set_virtual_keyboard_enabled);
ClassDB::bind_method(D_METHOD("is_virtual_keyboard_enabled"), &LineEdit::is_virtual_keyboard_enabled);
ClassDB::bind_method(D_METHOD("set_virtual_keyboard_type", "type"), &LineEdit::set_virtual_keyboard_type);
@@ -3203,6 +3236,7 @@ void LineEdit::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "expand_to_text_length"), "set_expand_to_text_length_enabled", "is_expand_to_text_length_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "virtual_keyboard_enabled"), "set_virtual_keyboard_enabled", "is_virtual_keyboard_enabled");
ADD_PROPERTY(PropertyInfo(Variant::INT, "virtual_keyboard_type", PROPERTY_HINT_ENUM, "Default,Multiline,Number,Decimal,Phone,Email,Password,URL"), "set_virtual_keyboard_type", "get_virtual_keyboard_type");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clear_button_enabled"), "set_clear_button_enabled", "is_clear_button_enabled");
diff --git a/scene/gui/line_edit.h b/scene/gui/line_edit.h
index 672c66cd32b5..709c64dc6ee5 100644
--- a/scene/gui/line_edit.h
+++ b/scene/gui/line_edit.h
@@ -122,6 +122,7 @@ class LineEdit : public Control {
PopupMenu *menu = nullptr;
PopupMenu *menu_dir = nullptr;
PopupMenu *menu_ctl = nullptr;
@@ -309,6 +310,9 @@ class LineEdit : public Control {
void select(int p_from = 0, int p_to = -1);
void select_all();
void selection_delete();
@@ -345,6 +349,8 @@ class LineEdit : public Control {
void set_caret_column(int p_column);
int get_caret_column() const;
+ int get_next_composite_character_column(int p_column) const;
+ int get_previous_composite_character_column(int p_column) const;
void set_max_length(int p_max_length);
int get_max_length() const;
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index 7e3bf4519dd6..4bc00d885788 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -3723,6 +3723,14 @@ bool TextEdit::is_emoji_menu_enabled() const {
+void TextEdit::set_backspace_deletes_composite_character_enabled(bool p_enabled) {
+bool TextEdit::is_backspace_deletes_composite_character_enabled() const {
void TextEdit::set_shortcut_keys_enabled(bool p_enabled) {
shortcut_keys_enabled = p_enabled;
@@ -6056,6 +6064,26 @@ int TextEdit::get_selection_origin_column(int p_caret) const {
return carets[p_caret].selection.origin_column;
+int TextEdit::get_next_composite_character_column(int p_line, int p_column) const {
+ return TS->shaped_text_next_character_pos(text.get_line_data(p_line)->get_rid(), (p_column));
+int TextEdit::get_previous_composite_character_column(int p_line, int p_column) const {
+ return TS->shaped_text_prev_character_pos(text.get_line_data(p_line)->get_rid(), p_column);
int TextEdit::get_selection_from_line(int p_caret) const {
ERR_FAIL_INDEX_V(p_caret, carets.size(), -1);
if (!has_selection(p_caret)) {
@@ -6957,6 +6985,9 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_emoji_menu_enabled", "enable"), &TextEdit::set_emoji_menu_enabled);
ClassDB::bind_method(D_METHOD("is_emoji_menu_enabled"), &TextEdit::is_emoji_menu_enabled);
+ ClassDB::bind_method(D_METHOD("set_backspace_deletes_composite_character_enabled", "enable"), &TextEdit::set_backspace_deletes_composite_character_enabled);
ClassDB::bind_method(D_METHOD("set_shortcut_keys_enabled", "enabled"), &TextEdit::set_shortcut_keys_enabled);
ClassDB::bind_method(D_METHOD("is_shortcut_keys_enabled"), &TextEdit::is_shortcut_keys_enabled);
@@ -7150,6 +7181,8 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_caret_column", "column", "adjust_viewport", "caret_index"), &TextEdit::set_caret_column, DEFVAL(true), DEFVAL(0));
ClassDB::bind_method(D_METHOD("get_caret_column", "caret_index"), &TextEdit::get_caret_column, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_next_composite_character_column", "line", "column"), &TextEdit::get_next_composite_character_column);
+ ClassDB::bind_method(D_METHOD("get_previous_composite_character_column", "line", "column"), &TextEdit::get_previous_composite_character_column);
ClassDB::bind_method(D_METHOD("get_caret_wrap_index", "caret_index"), &TextEdit::get_caret_wrap_index, DEFVAL(0));
@@ -7359,6 +7392,7 @@ void TextEdit::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_keys_enabled"), "set_shortcut_keys_enabled", "is_shortcut_keys_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "selecting_enabled"), "set_selecting_enabled", "is_selecting_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "deselect_on_focus_loss_enabled"), "set_deselect_on_focus_loss_enabled", "is_deselect_on_focus_loss_enabled");
@@ -7595,7 +7629,14 @@ void TextEdit::_backspace_internal(int p_caret) {
- int from_column = to_column > 0 ? (to_column - 1) : (text[to_line - 1].length());
+ from_column = text[to_line - 1].length();
+ } else if (caret_mid_grapheme_enabled || !backspace_deletes_composite_character_enabled) {
+ from_column = get_previous_composite_character_column(to_line, to_column);
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index 8f6a5be6e7fc..e0b785e7cf14 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -340,6 +340,7 @@ class TextEdit : public Control {
bool overtype_mode = false;
bool shortcut_keys_enabled = true;
bool virtual_keyboard_enabled = true;
bool middle_mouse_paste_enabled = true;
@@ -813,6 +814,9 @@ class TextEdit : public Control {
void set_shortcut_keys_enabled(bool p_enabled);
bool is_shortcut_keys_enabled() const;
@@ -960,6 +964,8 @@ class TextEdit : public Control {
void set_caret_column(int p_column, bool p_adjust_viewport = true, int p_caret = 0);
int get_caret_column(int p_caret = 0) const;
+ int get_next_composite_character_column(int p_line, int p_column) const;
+ int get_previous_composite_character_column(int p_line, int p_column) const;
int get_caret_wrap_index(int p_caret = 0) const; | [
"+\t\t\t\t[b]Note:[/b] To check at caret location use [code]get_previous_composite_character_column(get_caret_line(), get_caret_column())[/code]",
"+\t\t\tfrom_column = get_line(to_line - 1).length();",
"+\tint delete_char_offset = 1;",
"+\tif (!caret_mid_grapheme_enabled && backspace_deletes_composite_character_enabled) {",
"+int LineEdit::get_previous_composite_character_column(int p_column) const {",
"+\t\treturn TS->shaped_text_prev_character_pos(text_rid, p_column);",
"+\tClassDB::bind_method(D_METHOD(\"is_backspace_deletes_composite_character_enabled\"), &LineEdit::is_backspace_deletes_composite_character_enabled);",
"+\tif (p_column == text[p_line].length()) {",
"+\tClassDB::bind_method(D_METHOD(\"is_backspace_deletes_composite_character_enabled\"), &TextEdit::is_backspace_deletes_composite_character_enabled);"
] | [
67,
94,
113,
114,
138,
143,
179,
248,
273
] | {
"additions": 139,
"author": "Koyper",
"deletions": 5,
"html_url": "https://github.com/godotengine/godot/pull/105656",
"issue_id": 105656,
"merged_at": "2025-04-24T14:14:24Z",
"omission_probability": 0.1,
"pr_number": 105656,
"repo": "godotengine/godot",
"title": "[LineEdit/TextEdit] Add composite character backspace delete and get composite character positions",
"total_changes": 144
} |
703 | diff --git a/servers/audio/effects/audio_effect_pitch_shift.cpp b/servers/audio/effects/audio_effect_pitch_shift.cpp
index d8857c06c88b..3f8a459453a3 100644
--- a/servers/audio/effects/audio_effect_pitch_shift.cpp
+++ b/servers/audio/effects/audio_effect_pitch_shift.cpp
@@ -160,8 +160,13 @@ void SMBPitchShift::PitchShift(float pitchShift, long numSampsToProcess, long ff
/* ***************** PROCESSING ******************* */
/* this does the actual pitch shifting */
- memset(gSynMagn, 0, fftFrameSize*sizeof(float));
- memset(gSynFreq, 0, fftFrameSize*sizeof(float));
+ size_t fftBufferSize = static_cast<size_t>(fftFrameSize) * sizeof(float);
+ if (unlikely(fftBufferSize > MAX_FRAME_LENGTH)) {
+ ERR_PRINT_ONCE("Invalid FFT frame size for PitchShift. This is a bug, please report.");
+ return;
+ }
+ memset(gSynMagn, 0, fftBufferSize);
+ memset(gSynFreq, 0, fftBufferSize);
for (k = 0; k <= fftFrameSize2; k++) {
index = k*pitchShift;
if (index <= fftFrameSize2) {
@@ -214,7 +219,7 @@ void SMBPitchShift::PitchShift(float pitchShift, long numSampsToProcess, long ff
}
/* shift accumulator */
- memmove(gOutputAccum, gOutputAccum+stepSize, fftFrameSize*sizeof(float));
+ memmove(gOutputAccum, gOutputAccum+stepSize, fftBufferSize);
/* move input FIFO */
for (k = 0; k < inFifoLatency; k++) { gInFIFO[k] = gInFIFO[k+stepSize];
| diff --git a/servers/audio/effects/audio_effect_pitch_shift.cpp b/servers/audio/effects/audio_effect_pitch_shift.cpp
index d8857c06c88b..3f8a459453a3 100644
--- a/servers/audio/effects/audio_effect_pitch_shift.cpp
+++ b/servers/audio/effects/audio_effect_pitch_shift.cpp
@@ -160,8 +160,13 @@ void SMBPitchShift::PitchShift(float pitchShift, long numSampsToProcess, long ff
/* ***************** PROCESSING ******************* */
/* this does the actual pitch shifting */
- memset(gSynMagn, 0, fftFrameSize*sizeof(float));
- memset(gSynFreq, 0, fftFrameSize*sizeof(float));
+ size_t fftBufferSize = static_cast<size_t>(fftFrameSize) * sizeof(float);
+ if (unlikely(fftBufferSize > MAX_FRAME_LENGTH)) {
+ ERR_PRINT_ONCE("Invalid FFT frame size for PitchShift. This is a bug, please report.");
+ return;
+ }
+ memset(gSynMagn, 0, fftBufferSize);
+ memset(gSynFreq, 0, fftBufferSize);
for (k = 0; k <= fftFrameSize2; k++) {
index = k*pitchShift;
if (index <= fftFrameSize2) {
@@ -214,7 +219,7 @@ void SMBPitchShift::PitchShift(float pitchShift, long numSampsToProcess, long ff
}
/* shift accumulator */
- memmove(gOutputAccum, gOutputAccum+stepSize, fftFrameSize*sizeof(float));
+ memmove(gOutputAccum, gOutputAccum+stepSize, fftBufferSize);
/* move input FIFO */
for (k = 0; k < inFifoLatency; k++) { gInFIFO[k] = gInFIFO[k+stepSize]; | [] | [] | {
"additions": 8,
"author": "akien-mga",
"deletions": 3,
"html_url": "https://github.com/godotengine/godot/pull/105744",
"issue_id": 105744,
"merged_at": "2025-04-25T12:26:35Z",
"omission_probability": 0.1,
"pr_number": 105744,
"repo": "godotengine/godot",
"title": "AudioEffectPitchShift: 3rd attempt at fixing `-Wstringop-overflow` warning",
"total_changes": 11
} |
704 | diff --git a/core/crypto/crypto_core.cpp b/core/crypto/crypto_core.cpp
index 13852d517794..9d2c346e3ae1 100644
--- a/core/crypto/crypto_core.cpp
+++ b/core/crypto/crypto_core.cpp
@@ -214,8 +214,8 @@ Error CryptoCore::AESContext::decrypt_cfb(size_t p_length, uint8_t p_iv[16], con
}
// CryptoCore
-String CryptoCore::b64_encode_str(const uint8_t *p_src, int p_src_len) {
- int b64len = p_src_len / 3 * 4 + 4 + 1;
+String CryptoCore::b64_encode_str(const uint8_t *p_src, size_t p_src_len) {
+ size_t b64len = p_src_len / 3 * 4 + 4 + 1;
Vector<uint8_t> b64buff;
b64buff.resize(b64len);
uint8_t *w64 = b64buff.ptrw();
@@ -225,27 +225,27 @@ String CryptoCore::b64_encode_str(const uint8_t *p_src, int p_src_len) {
return ret ? String() : (const char *)&w64[0];
}
-Error CryptoCore::b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) {
+Error CryptoCore::b64_encode(uint8_t *r_dst, size_t p_dst_len, size_t *r_len, const uint8_t *p_src, size_t p_src_len) {
int ret = mbedtls_base64_encode(r_dst, p_dst_len, r_len, p_src, p_src_len);
return ret ? FAILED : OK;
}
-Error CryptoCore::b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) {
+Error CryptoCore::b64_decode(uint8_t *r_dst, size_t p_dst_len, size_t *r_len, const uint8_t *p_src, size_t p_src_len) {
int ret = mbedtls_base64_decode(r_dst, p_dst_len, r_len, p_src, p_src_len);
return ret ? FAILED : OK;
}
-Error CryptoCore::md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]) {
+Error CryptoCore::md5(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[16]) {
int ret = mbedtls_md5_ret(p_src, p_src_len, r_hash);
return ret ? FAILED : OK;
}
-Error CryptoCore::sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]) {
+Error CryptoCore::sha1(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[20]) {
int ret = mbedtls_sha1_ret(p_src, p_src_len, r_hash);
return ret ? FAILED : OK;
}
-Error CryptoCore::sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]) {
+Error CryptoCore::sha256(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[32]) {
int ret = mbedtls_sha256_ret(p_src, p_src_len, r_hash, 0);
return ret ? FAILED : OK;
}
diff --git a/core/crypto/crypto_core.h b/core/crypto/crypto_core.h
index 75455eb9ddad..8ef50fbcf7db 100644
--- a/core/crypto/crypto_core.h
+++ b/core/crypto/crypto_core.h
@@ -106,11 +106,11 @@ class CryptoCore {
Error decrypt_cfb(size_t p_length, uint8_t p_iv[16], const uint8_t *p_src, uint8_t *r_dst);
};
- static String b64_encode_str(const uint8_t *p_src, int p_src_len);
- static Error b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len);
- static Error b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len);
+ static String b64_encode_str(const uint8_t *p_src, size_t p_src_len);
+ static Error b64_encode(uint8_t *r_dst, size_t p_dst_len, size_t *r_len, const uint8_t *p_src, size_t p_src_len);
+ static Error b64_decode(uint8_t *r_dst, size_t p_dst_len, size_t *r_len, const uint8_t *p_src, size_t p_src_len);
- static Error md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]);
- static Error sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]);
- static Error sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]);
+ static Error md5(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[16]);
+ static Error sha1(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[20]);
+ static Error sha256(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[32]);
};
| diff --git a/core/crypto/crypto_core.cpp b/core/crypto/crypto_core.cpp
index 13852d517794..9d2c346e3ae1 100644
--- a/core/crypto/crypto_core.cpp
+++ b/core/crypto/crypto_core.cpp
@@ -214,8 +214,8 @@ Error CryptoCore::AESContext::decrypt_cfb(size_t p_length, uint8_t p_iv[16], con
// CryptoCore
-String CryptoCore::b64_encode_str(const uint8_t *p_src, int p_src_len) {
- int b64len = p_src_len / 3 * 4 + 4 + 1;
+String CryptoCore::b64_encode_str(const uint8_t *p_src, size_t p_src_len) {
+ size_t b64len = p_src_len / 3 * 4 + 4 + 1;
Vector<uint8_t> b64buff;
b64buff.resize(b64len);
uint8_t *w64 = b64buff.ptrw();
@@ -225,27 +225,27 @@ String CryptoCore::b64_encode_str(const uint8_t *p_src, int p_src_len) {
return ret ? String() : (const char *)&w64[0];
+Error CryptoCore::b64_encode(uint8_t *r_dst, size_t p_dst_len, size_t *r_len, const uint8_t *p_src, size_t p_src_len) {
int ret = mbedtls_base64_encode(r_dst, p_dst_len, r_len, p_src, p_src_len);
int ret = mbedtls_base64_decode(r_dst, p_dst_len, r_len, p_src, p_src_len);
-Error CryptoCore::md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]) {
+Error CryptoCore::md5(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[16]) {
int ret = mbedtls_md5_ret(p_src, p_src_len, r_hash);
-Error CryptoCore::sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]) {
+Error CryptoCore::sha1(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[20]) {
int ret = mbedtls_sha1_ret(p_src, p_src_len, r_hash);
-Error CryptoCore::sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]) {
+Error CryptoCore::sha256(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[32]) {
int ret = mbedtls_sha256_ret(p_src, p_src_len, r_hash, 0);
diff --git a/core/crypto/crypto_core.h b/core/crypto/crypto_core.h
index 75455eb9ddad..8ef50fbcf7db 100644
--- a/core/crypto/crypto_core.h
+++ b/core/crypto/crypto_core.h
@@ -106,11 +106,11 @@ class CryptoCore {
Error decrypt_cfb(size_t p_length, uint8_t p_iv[16], const uint8_t *p_src, uint8_t *r_dst);
};
- static String b64_encode_str(const uint8_t *p_src, int p_src_len);
- static Error b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len);
- static Error b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len);
+ static String b64_encode_str(const uint8_t *p_src, size_t p_src_len);
+ static Error b64_encode(uint8_t *r_dst, size_t p_dst_len, size_t *r_len, const uint8_t *p_src, size_t p_src_len);
+ static Error b64_decode(uint8_t *r_dst, size_t p_dst_len, size_t *r_len, const uint8_t *p_src, size_t p_src_len);
- static Error md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]);
- static Error sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]);
+ static Error md5(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[16]);
+ static Error sha1(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[20]);
+ static Error sha256(const uint8_t *p_src, size_t p_src_len, unsigned char r_hash[32]);
}; | [
"-Error CryptoCore::b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) {",
"-Error CryptoCore::b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) {",
"+Error CryptoCore::b64_decode(uint8_t *r_dst, size_t p_dst_len, size_t *r_len, const uint8_t *p_src, size_t p_src_len) {",
"-\tstatic Error sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]);"
] | [
19,
25,
26,
64
] | {
"additions": 13,
"author": "akien-mga",
"deletions": 13,
"html_url": "https://github.com/godotengine/godot/pull/104960",
"issue_id": 104960,
"merged_at": "2025-04-03T14:34:53Z",
"omission_probability": 0.1,
"pr_number": 104960,
"repo": "godotengine/godot",
"title": "CryptoCore: Use `size_t` for buffer sizes to fix encoding/sums of 2.0+ GiB files",
"total_changes": 26
} |
705 | diff --git a/core/templates/local_vector.h b/core/templates/local_vector.h
index 547006d1915d..0cbd42377f06 100644
--- a/core/templates/local_vector.h
+++ b/core/templates/local_vector.h
@@ -126,11 +126,14 @@ class LocalVector {
return occurrences;
}
- void invert() {
+ void reverse() {
for (U i = 0; i < count / 2; i++) {
SWAP(data[i], data[count - i - 1]);
}
}
+#ifndef DISABLE_DEPRECATED
+ [[deprecated("Use reverse() instead")]] void invert() { reverse(); }
+#endif
_FORCE_INLINE_ void clear() { resize(0); }
_FORCE_INLINE_ void reset() {
diff --git a/modules/navigation_2d/2d/nav_mesh_queries_2d.h b/modules/navigation_2d/2d/nav_mesh_queries_2d.h
index d15913ce484b..0bb9ecd1a797 100644
--- a/modules/navigation_2d/2d/nav_mesh_queries_2d.h
+++ b/modules/navigation_2d/2d/nav_mesh_queries_2d.h
@@ -103,10 +103,10 @@ class NavMeshQueries2D {
}
void path_reverse() {
- path_points.invert();
- path_meta_point_types.invert();
- path_meta_point_rids.invert();
- path_meta_point_owners.invert();
+ path_points.reverse();
+ path_meta_point_types.reverse();
+ path_meta_point_rids.reverse();
+ path_meta_point_owners.reverse();
}
};
diff --git a/modules/navigation_3d/3d/nav_mesh_queries_3d.h b/modules/navigation_3d/3d/nav_mesh_queries_3d.h
index ca9eea323f67..5f4854f9842f 100644
--- a/modules/navigation_3d/3d/nav_mesh_queries_3d.h
+++ b/modules/navigation_3d/3d/nav_mesh_queries_3d.h
@@ -104,10 +104,10 @@ class NavMeshQueries3D {
}
void path_reverse() {
- path_points.invert();
- path_meta_point_types.invert();
- path_meta_point_rids.invert();
- path_meta_point_owners.invert();
+ path_points.reverse();
+ path_meta_point_types.reverse();
+ path_meta_point_rids.reverse();
+ path_meta_point_owners.reverse();
}
};
| diff --git a/core/templates/local_vector.h b/core/templates/local_vector.h
index 547006d1915d..0cbd42377f06 100644
--- a/core/templates/local_vector.h
+++ b/core/templates/local_vector.h
@@ -126,11 +126,14 @@ class LocalVector {
return occurrences;
- void invert() {
+ void reverse() {
for (U i = 0; i < count / 2; i++) {
SWAP(data[i], data[count - i - 1]);
+#ifndef DISABLE_DEPRECATED
+ [[deprecated("Use reverse() instead")]] void invert() { reverse(); }
+#endif
_FORCE_INLINE_ void clear() { resize(0); }
_FORCE_INLINE_ void reset() {
diff --git a/modules/navigation_2d/2d/nav_mesh_queries_2d.h b/modules/navigation_2d/2d/nav_mesh_queries_2d.h
index d15913ce484b..0bb9ecd1a797 100644
--- a/modules/navigation_2d/2d/nav_mesh_queries_2d.h
+++ b/modules/navigation_2d/2d/nav_mesh_queries_2d.h
@@ -103,10 +103,10 @@ class NavMeshQueries2D {
diff --git a/modules/navigation_3d/3d/nav_mesh_queries_3d.h b/modules/navigation_3d/3d/nav_mesh_queries_3d.h
index ca9eea323f67..5f4854f9842f 100644
--- a/modules/navigation_3d/3d/nav_mesh_queries_3d.h
+++ b/modules/navigation_3d/3d/nav_mesh_queries_3d.h
@@ -104,10 +104,10 @@ class NavMeshQueries3D { | [] | [] | {
"additions": 12,
"author": "Ivorforce",
"deletions": 9,
"html_url": "https://github.com/godotengine/godot/pull/101027",
"issue_id": 101027,
"merged_at": "2025-04-24T22:23:37Z",
"omission_probability": 0.1,
"pr_number": 101027,
"repo": "godotengine/godot",
"title": "Rename `LocalVector.invert()` -> `LocalVector.reverse()` to match the `Vector`, `String` and `List` APIs.",
"total_changes": 21
} |
706 | diff --git a/doc/classes/ResourceImporterScene.xml b/doc/classes/ResourceImporterScene.xml
index 1565a244fe23..f14eb6d1e8ff 100644
--- a/doc/classes/ResourceImporterScene.xml
+++ b/doc/classes/ResourceImporterScene.xml
@@ -68,8 +68,11 @@
<member name="nodes/root_type" type="String" setter="" getter="" default="""">
Override for the root node type. If empty, the root node will use what the scene specifies, or [Node3D] if the scene does not specify a root type. Using a node type that inherits from [Node3D] is recommended. Otherwise, you'll lose the ability to position the node directly in the 3D editor.
</member>
+ <member name="nodes/use_name_suffixes" type="bool" setter="" getter="" default="true">
+ If [code]true[/code], will use suffixes in the names of imported objects such as nodes and resources to determine types and properties, such as [code]-noimp[/code] to skip import of a node or animation, [code]-alpha[/code] to enable alpha transparency on a material, and [code]-vcol[/code] to enable vertex colors on a material. Disabling this makes editor-imported files more similar to the original files, and more similar to files imported at runtime. See [url=$DOCS_URL/tutorials/assets_pipeline/importing_3d_scenes/node_type_customization.html]Node type customization using name suffixes[/url] for more information.
+ </member>
<member name="nodes/use_node_type_suffixes" type="bool" setter="" getter="" default="true">
- If [code]true[/code], use suffixes in the node names to determine the node type, such as [code]-col[/code] for collision shapes. Disabling this makes editor-imported files more similar to the original files, and more similar to importing files at runtime. See [url=$DOCS_URL/tutorials/assets_pipeline/importing_3d_scenes/node_type_customization.html]Node type customization using name suffixes[/url] for more information.
+ If [code]true[/code], will use suffixes in the node names to determine the node type, such as [code]-col[/code] for collision shapes. This is only used when [member nodes/use_name_suffixes] is [code]true[/code]. Disabling this makes editor-imported files more similar to the original files, and more similar to files imported at runtime. See [url=$DOCS_URL/tutorials/assets_pipeline/importing_3d_scenes/node_type_customization.html]Node type customization using name suffixes[/url] for more information.
</member>
<member name="skins/use_named_skins" type="bool" setter="" getter="" default="true">
If checked, use named [Skin]s for animation. The [MeshInstance3D] node contains 3 properties of relevance here: a skeleton [NodePath] pointing to the [Skeleton3D] node (usually [code]..[/code]), a mesh, and a skin:
diff --git a/editor/import/3d/resource_importer_scene.cpp b/editor/import/3d/resource_importer_scene.cpp
index b05e7c2aaf28..5b4195806029 100644
--- a/editor/import/3d/resource_importer_scene.cpp
+++ b/editor/import/3d/resource_importer_scene.cpp
@@ -303,6 +303,9 @@ bool ResourceImporterScene::get_option_visibility(const String &p_path, const St
}
}
+ if (p_option == "nodes/use_node_type_suffixes" && p_options.has("nodes/use_name_suffixes")) {
+ return p_options["nodes/use_name_suffixes"];
+ }
if (p_option == "meshes/lightmap_texel_size" && int(p_options["meshes/light_baking"]) != 2) {
// Only display the lightmap texel size import option when using the Static Lightmaps light baking mode.
return false;
@@ -639,6 +642,14 @@ void _apply_permanent_scale_to_descendants(Node *p_root_node, Vector3 p_scale) {
}
Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, HashMap<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> &r_collision_map, Pair<PackedVector3Array, PackedInt32Array> *r_occluder_arrays, List<Pair<NodePath, Node *>> &r_node_renames, const HashMap<StringName, Variant> &p_options) {
+ bool use_name_suffixes = true;
+ if (p_options.has("nodes/use_name_suffixes")) {
+ use_name_suffixes = p_options["nodes/use_name_suffixes"];
+ }
+ if (!use_name_suffixes) {
+ return p_node;
+ }
+
// Children first.
for (int i = 0; i < p_node->get_child_count(); i++) {
Node *r = _pre_fix_node(p_node->get_child(i), p_root, r_collision_map, r_occluder_arrays, r_node_renames, p_options);
@@ -2409,6 +2420,7 @@ void ResourceImporterScene::get_import_options(const String &p_path, List<Import
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/apply_root_scale"), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "nodes/root_scale", PROPERTY_HINT_RANGE, "0.001,1000,0.001"), 1.0));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/import_as_skeleton_bones"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/use_name_suffixes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/use_node_type_suffixes"), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/ensure_tangents"), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/generate_lods"), true));
| diff --git a/doc/classes/ResourceImporterScene.xml b/doc/classes/ResourceImporterScene.xml
index 1565a244fe23..f14eb6d1e8ff 100644
--- a/doc/classes/ResourceImporterScene.xml
+++ b/doc/classes/ResourceImporterScene.xml
@@ -68,8 +68,11 @@
<member name="nodes/root_type" type="String" setter="" getter="" default="""">
Override for the root node type. If empty, the root node will use what the scene specifies, or [Node3D] if the scene does not specify a root type. Using a node type that inherits from [Node3D] is recommended. Otherwise, you'll lose the ability to position the node directly in the 3D editor.
+ <member name="nodes/use_name_suffixes" type="bool" setter="" getter="" default="true">
+ If [code]true[/code], will use suffixes in the names of imported objects such as nodes and resources to determine types and properties, such as [code]-noimp[/code] to skip import of a node or animation, [code]-alpha[/code] to enable alpha transparency on a material, and [code]-vcol[/code] to enable vertex colors on a material. Disabling this makes editor-imported files more similar to the original files, and more similar to files imported at runtime. See [url=$DOCS_URL/tutorials/assets_pipeline/importing_3d_scenes/node_type_customization.html]Node type customization using name suffixes[/url] for more information.
+ </member>
<member name="nodes/use_node_type_suffixes" type="bool" setter="" getter="" default="true">
- If [code]true[/code], use suffixes in the node names to determine the node type, such as [code]-col[/code] for collision shapes. Disabling this makes editor-imported files more similar to the original files, and more similar to importing files at runtime. See [url=$DOCS_URL/tutorials/assets_pipeline/importing_3d_scenes/node_type_customization.html]Node type customization using name suffixes[/url] for more information.
+ If [code]true[/code], will use suffixes in the node names to determine the node type, such as [code]-col[/code] for collision shapes. This is only used when [member nodes/use_name_suffixes] is [code]true[/code]. Disabling this makes editor-imported files more similar to the original files, and more similar to files imported at runtime. See [url=$DOCS_URL/tutorials/assets_pipeline/importing_3d_scenes/node_type_customization.html]Node type customization using name suffixes[/url] for more information.
<member name="skins/use_named_skins" type="bool" setter="" getter="" default="true">
If checked, use named [Skin]s for animation. The [MeshInstance3D] node contains 3 properties of relevance here: a skeleton [NodePath] pointing to the [Skeleton3D] node (usually [code]..[/code]), a mesh, and a skin:
diff --git a/editor/import/3d/resource_importer_scene.cpp b/editor/import/3d/resource_importer_scene.cpp
index b05e7c2aaf28..5b4195806029 100644
--- a/editor/import/3d/resource_importer_scene.cpp
+++ b/editor/import/3d/resource_importer_scene.cpp
@@ -303,6 +303,9 @@ bool ResourceImporterScene::get_option_visibility(const String &p_path, const St
}
}
+ if (p_option == "nodes/use_node_type_suffixes" && p_options.has("nodes/use_name_suffixes")) {
+ return p_options["nodes/use_name_suffixes"];
if (p_option == "meshes/lightmap_texel_size" && int(p_options["meshes/light_baking"]) != 2) {
// Only display the lightmap texel size import option when using the Static Lightmaps light baking mode.
return false;
@@ -639,6 +642,14 @@ void _apply_permanent_scale_to_descendants(Node *p_root_node, Vector3 p_scale) {
}
Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, HashMap<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> &r_collision_map, Pair<PackedVector3Array, PackedInt32Array> *r_occluder_arrays, List<Pair<NodePath, Node *>> &r_node_renames, const HashMap<StringName, Variant> &p_options) {
+ bool use_name_suffixes = true;
+ use_name_suffixes = p_options["nodes/use_name_suffixes"];
+ if (!use_name_suffixes) {
+ return p_node;
+
// Children first.
for (int i = 0; i < p_node->get_child_count(); i++) {
Node *r = _pre_fix_node(p_node->get_child(i), p_root, r_collision_map, r_occluder_arrays, r_node_renames, p_options);
@@ -2409,6 +2420,7 @@ void ResourceImporterScene::get_import_options(const String &p_path, List<Import
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/apply_root_scale"), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "nodes/root_scale", PROPERTY_HINT_RANGE, "0.001,1000,0.001"), 1.0));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/import_as_skeleton_bones"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/use_name_suffixes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/use_node_type_suffixes"), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/ensure_tangents"), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/generate_lods"), true)); | [
"+\tif (p_options.has(\"nodes/use_name_suffixes\")) {"
] | [
36
] | {
"additions": 16,
"author": "aaronfranke",
"deletions": 1,
"html_url": "https://github.com/godotengine/godot/pull/105014",
"issue_id": 105014,
"merged_at": "2025-04-24T22:23:37Z",
"omission_probability": 0.1,
"pr_number": 105014,
"repo": "godotengine/godot",
"title": "Allow completely opting out of name suffix magic in 3D scene import",
"total_changes": 17
} |
707 | diff --git a/modules/gltf/doc_classes/GLTFDocument.xml b/modules/gltf/doc_classes/GLTFDocument.xml
index 47ffc624bad9..46492958a1d2 100644
--- a/modules/gltf/doc_classes/GLTFDocument.xml
+++ b/modules/gltf/doc_classes/GLTFDocument.xml
@@ -126,6 +126,9 @@
How to process the root node during export. See [enum RootNodeMode] for details. The default and recommended value is [constant ROOT_NODE_MODE_SINGLE_ROOT].
[b]Note:[/b] Regardless of how the glTF file is exported, when importing, the root node type and name can be overridden in the scene import settings tab.
</member>
+ <member name="visibility_mode" type="int" setter="set_visibility_mode" getter="get_visibility_mode" enum="GLTFDocument.VisibilityMode" default="0">
+ How to deal with node visibility during export. This setting does nothing if all nodes are visible. See [enum VisibilityMode] for details. The default and recommended value is [constant VISIBILITY_MODE_INCLUDE_REQUIRED], which uses the [code]KHR_node_visibility[/code] extension.
+ </member>
</members>
<constants>
<constant name="ROOT_NODE_MODE_SINGLE_ROOT" value="0" enum="RootNodeMode">
@@ -137,5 +140,14 @@
<constant name="ROOT_NODE_MODE_MULTI_ROOT" value="2" enum="RootNodeMode">
Treat the Godot scene's root node as the name of the glTF scene, and add all of its children as root nodes of the glTF file. This uses only vanilla glTF features. This avoids an extra root node, but only the name of the Godot scene's root node will be preserved, as it will not be saved as a node.
</constant>
+ <constant name="VISIBILITY_MODE_INCLUDE_REQUIRED" value="0" enum="VisibilityMode">
+ If the scene contains any non-visible nodes, include them, mark them as non-visible with [code]KHR_node_visibility[/code], and require that importers respect their non-visibility. Downside: If the importer does not support [code]KHR_node_visibility[/code], the file cannot be imported.
+ </constant>
+ <constant name="VISIBILITY_MODE_INCLUDE_OPTIONAL" value="1" enum="VisibilityMode">
+ If the scene contains any non-visible nodes, include them, mark them as non-visible with [code]KHR_node_visibility[/code], and do not impose any requirements on importers. Downside: If the importer does not support [code]KHR_node_visibility[/code], invisible objects will be visible.
+ </constant>
+ <constant name="VISIBILITY_MODE_EXCLUDE" value="2" enum="VisibilityMode">
+ If the scene contains any non-visible nodes, do not include them in the export. This is the same as the behavior in Godot 4.4 and earlier. Downside: Invisible nodes will not exist in the exported file.
+ </constant>
</constants>
</class>
diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml
index ed05fde70293..7b09ae91256b 100644
--- a/modules/gltf/doc_classes/GLTFNode.xml
+++ b/modules/gltf/doc_classes/GLTFNode.xml
@@ -83,6 +83,9 @@
<member name="skin" type="int" setter="set_skin" getter="get_skin" default="-1">
If this glTF node has a skin, the index of the [GLTFSkin] in the [GLTFState] that describes the skin's properties. If -1, this node does not have a skin.
</member>
+ <member name="visible" type="bool" setter="set_visible" getter="get_visible" default="true">
+ If [code]true[/code], the GLTF node is visible. If [code]false[/code], the GLTF node is not visible. This is translated to the [member Node3D.visible] property in the Godot scene, and is exported to [code]KHR_node_visibility[/code] when [code]false[/code].
+ </member>
<member name="xform" type="Transform3D" setter="set_xform" getter="get_xform" default="Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)">
The transform of the glTF node relative to its parent. This property is usually unused since the position, rotation, and scale properties are preferred.
</member>
diff --git a/modules/gltf/editor/editor_scene_exporter_gltf_settings.cpp b/modules/gltf/editor/editor_scene_exporter_gltf_settings.cpp
index 372314578f57..c0dbe4a61eae 100644
--- a/modules/gltf/editor/editor_scene_exporter_gltf_settings.cpp
+++ b/modules/gltf/editor/editor_scene_exporter_gltf_settings.cpp
@@ -50,6 +50,10 @@ bool EditorSceneExporterGLTFSettings::_set(const StringName &p_name, const Varia
_document->set_root_node_mode((GLTFDocument::RootNodeMode)(int64_t)p_value);
return true;
}
+ if (p_name == StringName("visibility_mode")) {
+ _document->set_visibility_mode((GLTFDocument::VisibilityMode)(int64_t)p_value);
+ return true;
+ }
return false;
}
@@ -70,6 +74,10 @@ bool EditorSceneExporterGLTFSettings::_get(const StringName &p_name, Variant &r_
r_ret = _document->get_root_node_mode();
return true;
}
+ if (p_name == StringName("visibility_mode")) {
+ r_ret = _document->get_visibility_mode();
+ return true;
+ }
return false;
}
@@ -128,6 +136,21 @@ String get_friendly_config_prefix(Ref<GLTFDocumentExtension> p_extension) {
return "Unknown GLTFDocumentExtension";
}
+bool is_any_node_invisible(Node *p_node) {
+ if (p_node->has_method("is_visible")) {
+ bool visible = p_node->call("is_visible");
+ if (!visible) {
+ return true;
+ }
+ }
+ for (int i = 0; i < p_node->get_child_count(); i++) {
+ if (is_any_node_invisible(p_node->get_child(i))) {
+ return true;
+ }
+ }
+ return false;
+}
+
// Run this before popping up the export settings, because the extensions may have changed.
void EditorSceneExporterGLTFSettings::generate_property_list(Ref<GLTFDocument> p_document, Node *p_root) {
_property_list.clear();
@@ -168,6 +191,11 @@ void EditorSceneExporterGLTFSettings::generate_property_list(Ref<GLTFDocument> p
_property_list.push_back(lossy_quality_prop);
PropertyInfo root_node_mode_prop = PropertyInfo(Variant::INT, "root_node_mode", PROPERTY_HINT_ENUM, "Single Root,Keep Root,Multi Root");
_property_list.push_back(root_node_mode_prop);
+ // If the scene contains any non-visible nodes, show the visibility mode setting.
+ if (p_root != nullptr && is_any_node_invisible(p_root)) {
+ PropertyInfo visibility_mode_prop = PropertyInfo(Variant::INT, "visibility_mode", PROPERTY_HINT_ENUM, "Include & Required,Include & Optional,Exclude");
+ _property_list.push_back(visibility_mode_prop);
+ }
}
String EditorSceneExporterGLTFSettings::get_copyright() const {
diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp
index 7dc7a2bccaeb..5430bffa66c7 100644
--- a/modules/gltf/gltf_document.cpp
+++ b/modules/gltf/gltf_document.cpp
@@ -443,6 +443,17 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> p_state) {
extensions["KHR_lights_punctual"] = lights_punctual;
lights_punctual["light"] = gltf_node->light;
}
+ if (!gltf_node->visible) {
+ Dictionary khr_node_visibility;
+ extensions["KHR_node_visibility"] = khr_node_visibility;
+ khr_node_visibility["visible"] = gltf_node->visible;
+ if (!p_state->extensions_used.has("KHR_node_visibility")) {
+ p_state->extensions_used.push_back("KHR_node_visibility");
+ if (_visibility_mode == VISIBILITY_MODE_INCLUDE_REQUIRED) {
+ p_state->extensions_required.push_back("KHR_node_visibility");
+ }
+ }
+ }
if (gltf_node->mesh != -1) {
node["mesh"] = gltf_node->mesh;
}
@@ -637,6 +648,12 @@ Error GLTFDocument::_parse_nodes(Ref<GLTFState> p_state) {
node->light = light;
}
}
+ if (extensions.has("KHR_node_visibility")) {
+ Dictionary khr_node_visibility = extensions["KHR_node_visibility"];
+ if (khr_node_visibility.has("visible")) {
+ node->visible = khr_node_visibility["visible"];
+ }
+ }
for (Ref<GLTFDocumentExtension> ext : document_extensions) {
ERR_CONTINUE(ext.is_null());
Error err = ext->parse_node_extensions(p_state, node, extensions);
@@ -5844,11 +5861,6 @@ Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> p_state, const GLTFNodeIn
}
void GLTFDocument::_convert_scene_node(Ref<GLTFState> p_state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) {
- bool retflag = true;
- _check_visibility(p_current, retflag);
- if (retflag) {
- return;
- }
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint() && p_gltf_root != -1 && p_current->get_owner() == nullptr) {
WARN_VERBOSE("glTF export warning: Node '" + p_current->get_name() + "' has no owner. This is likely a temporary node generated by a @tool script. This would not be saved when saving the Godot scene, therefore it will not be exported to glTF.");
@@ -5857,6 +5869,13 @@ void GLTFDocument::_convert_scene_node(Ref<GLTFState> p_state, Node *p_current,
#endif // TOOLS_ENABLED
Ref<GLTFNode> gltf_node;
gltf_node.instantiate();
+ if (p_current->has_method("is_visible")) {
+ bool visible = p_current->call("is_visible");
+ if (!visible && _visibility_mode == VISIBILITY_MODE_EXCLUDE) {
+ return;
+ }
+ gltf_node->visible = visible;
+ }
gltf_node->set_original_name(p_current->get_name());
gltf_node->set_name(_gen_unique_name(p_state, p_current->get_name()));
gltf_node->merge_meta_from(p_current);
@@ -5979,19 +5998,6 @@ void GLTFDocument::_convert_csg_shape_to_gltf(CSGShape3D *p_current, GLTFNodeInd
#endif // MODULE_CSG_ENABLED
}
-void GLTFDocument::_check_visibility(Node *p_node, bool &r_retflag) {
- r_retflag = true;
- Node3D *spatial = Object::cast_to<Node3D>(p_node);
- Node2D *node_2d = Object::cast_to<Node2D>(p_node);
- if (node_2d && !node_2d->is_visible()) {
- return;
- }
- if (spatial && !spatial->is_visible()) {
- return;
- }
- r_retflag = false;
-}
-
void GLTFDocument::_convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
ERR_FAIL_NULL(camera);
GLTFCameraIndex camera_index = _convert_camera(p_state, camera);
@@ -6275,6 +6281,7 @@ void GLTFDocument::_generate_scene_node(Ref<GLTFState> p_state, const GLTFNodeIn
if (!gltf_node_name.is_empty()) {
current_node->set_name(gltf_node_name);
}
+ current_node->set_visible(gltf_node->visible);
// Note: p_scene_parent and p_scene_root must either both be null or both be valid.
if (p_scene_root == nullptr) {
// If the root node argument is null, this is the root node.
@@ -8165,12 +8172,18 @@ void GLTFDocument::_bind_methods() {
BIND_ENUM_CONSTANT(ROOT_NODE_MODE_KEEP_ROOT);
BIND_ENUM_CONSTANT(ROOT_NODE_MODE_MULTI_ROOT);
+ BIND_ENUM_CONSTANT(VISIBILITY_MODE_INCLUDE_REQUIRED);
+ BIND_ENUM_CONSTANT(VISIBILITY_MODE_INCLUDE_OPTIONAL);
+ BIND_ENUM_CONSTANT(VISIBILITY_MODE_EXCLUDE);
+
ClassDB::bind_method(D_METHOD("set_image_format", "image_format"), &GLTFDocument::set_image_format);
ClassDB::bind_method(D_METHOD("get_image_format"), &GLTFDocument::get_image_format);
ClassDB::bind_method(D_METHOD("set_lossy_quality", "lossy_quality"), &GLTFDocument::set_lossy_quality);
ClassDB::bind_method(D_METHOD("get_lossy_quality"), &GLTFDocument::get_lossy_quality);
ClassDB::bind_method(D_METHOD("set_root_node_mode", "root_node_mode"), &GLTFDocument::set_root_node_mode);
ClassDB::bind_method(D_METHOD("get_root_node_mode"), &GLTFDocument::get_root_node_mode);
+ ClassDB::bind_method(D_METHOD("set_visibility_mode", "visibility_mode"), &GLTFDocument::set_visibility_mode);
+ ClassDB::bind_method(D_METHOD("get_visibility_mode"), &GLTFDocument::get_visibility_mode);
ClassDB::bind_method(D_METHOD("append_from_file", "path", "state", "flags", "base_path"),
&GLTFDocument::append_from_file, DEFVAL(0), DEFVAL(String()));
ClassDB::bind_method(D_METHOD("append_from_buffer", "bytes", "base_path", "state", "flags"),
@@ -8187,6 +8200,7 @@ void GLTFDocument::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING, "image_format"), "set_image_format", "get_image_format");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lossy_quality"), "set_lossy_quality", "get_lossy_quality");
ADD_PROPERTY(PropertyInfo(Variant::INT, "root_node_mode"), "set_root_node_mode", "get_root_node_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_mode"), "set_visibility_mode", "get_visibility_mode");
ClassDB::bind_static_method("GLTFDocument", D_METHOD("import_object_model_property", "state", "json_pointer"), &GLTFDocument::import_object_model_property);
ClassDB::bind_static_method("GLTFDocument", D_METHOD("export_object_model_property", "state", "node_path", "godot_node", "gltf_node_index"), &GLTFDocument::export_object_model_property);
@@ -8257,6 +8271,7 @@ HashSet<String> GLTFDocument::get_supported_gltf_extensions_hashset() {
supported_extensions.insert("KHR_materials_emissive_strength");
supported_extensions.insert("KHR_materials_pbrSpecularGlossiness");
supported_extensions.insert("KHR_materials_unlit");
+ supported_extensions.insert("KHR_node_visibility");
supported_extensions.insert("KHR_texture_transform");
for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
ERR_CONTINUE(ext.is_null());
@@ -8657,6 +8672,14 @@ GLTFDocument::RootNodeMode GLTFDocument::get_root_node_mode() const {
return _root_node_mode;
}
+void GLTFDocument::set_visibility_mode(VisibilityMode p_visibility_mode) {
+ _visibility_mode = p_visibility_mode;
+}
+
+GLTFDocument::VisibilityMode GLTFDocument::get_visibility_mode() const {
+ return _visibility_mode;
+}
+
String GLTFDocument::_gen_unique_name_static(HashSet<String> &r_unique_names, const String &p_name) {
const String s_name = p_name.validate_node_name();
diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h
index 38e668606d8c..0cddb28c23ad 100644
--- a/modules/gltf/gltf_document.h
+++ b/modules/gltf/gltf_document.h
@@ -60,6 +60,11 @@ class GLTFDocument : public Resource {
ROOT_NODE_MODE_KEEP_ROOT,
ROOT_NODE_MODE_MULTI_ROOT,
};
+ enum VisibilityMode {
+ VISIBILITY_MODE_INCLUDE_REQUIRED,
+ VISIBILITY_MODE_INCLUDE_OPTIONAL,
+ VISIBILITY_MODE_EXCLUDE,
+ };
private:
int _naming_version = 1;
@@ -67,6 +72,7 @@ class GLTFDocument : public Resource {
float _lossy_quality = 0.75f;
Ref<GLTFDocumentExtension> _image_save_extension;
RootNodeMode _root_node_mode = RootNodeMode::ROOT_NODE_MODE_SINGLE_ROOT;
+ VisibilityMode _visibility_mode = VisibilityMode::VISIBILITY_MODE_INCLUDE_REQUIRED;
protected:
static void _bind_methods();
@@ -94,6 +100,8 @@ class GLTFDocument : public Resource {
float get_lossy_quality() const;
void set_root_node_mode(RootNodeMode p_root_node_mode);
RootNodeMode get_root_node_mode() const;
+ void set_visibility_mode(VisibilityMode p_visibility_mode);
+ VisibilityMode get_visibility_mode() const;
static String _gen_unique_name_static(HashSet<String> &r_unique_names, const String &p_name);
private:
@@ -378,3 +386,4 @@ class GLTFDocument : public Resource {
};
VARIANT_ENUM_CAST(GLTFDocument::RootNodeMode);
+VARIANT_ENUM_CAST(GLTFDocument::VisibilityMode);
diff --git a/modules/gltf/structures/gltf_node.cpp b/modules/gltf/structures/gltf_node.cpp
index 1626313551ef..8a42ae3e8d86 100644
--- a/modules/gltf/structures/gltf_node.cpp
+++ b/modules/gltf/structures/gltf_node.cpp
@@ -60,6 +60,8 @@ void GLTFNode::_bind_methods() {
ClassDB::bind_method(D_METHOD("append_child_index", "child_index"), &GLTFNode::append_child_index);
ClassDB::bind_method(D_METHOD("get_light"), &GLTFNode::get_light);
ClassDB::bind_method(D_METHOD("set_light", "light"), &GLTFNode::set_light);
+ ClassDB::bind_method(D_METHOD("get_visible"), &GLTFNode::get_visible);
+ ClassDB::bind_method(D_METHOD("set_visible", "visible"), &GLTFNode::set_visible);
ClassDB::bind_method(D_METHOD("get_additional_data", "extension_name"), &GLTFNode::get_additional_data);
ClassDB::bind_method(D_METHOD("set_additional_data", "extension_name", "additional_data"), &GLTFNode::set_additional_data);
ClassDB::bind_method(D_METHOD("get_scene_node_path", "gltf_state", "handle_skeletons"), &GLTFNode::get_scene_node_path, DEFVAL(true));
@@ -77,6 +79,7 @@ void GLTFNode::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale"), "set_scale", "get_scale"); // Vector3
ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "children"), "set_children", "get_children"); // Vector<int>
ADD_PROPERTY(PropertyInfo(Variant::INT, "light"), "set_light", "get_light"); // GLTFLightIndex
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "get_visible"); // bool
}
String GLTFNode::get_original_name() {
@@ -186,6 +189,14 @@ void GLTFNode::set_light(GLTFLightIndex p_light) {
light = p_light;
}
+bool GLTFNode::get_visible() {
+ return visible;
+}
+
+void GLTFNode::set_visible(bool p_visible) {
+ visible = p_visible;
+}
+
Variant GLTFNode::get_additional_data(const StringName &p_extension_name) {
return additional_data[p_extension_name];
}
diff --git a/modules/gltf/structures/gltf_node.h b/modules/gltf/structures/gltf_node.h
index b0f75eea3bd3..41235de7366a 100644
--- a/modules/gltf/structures/gltf_node.h
+++ b/modules/gltf/structures/gltf_node.h
@@ -50,6 +50,7 @@ class GLTFNode : public Resource {
GLTFSkinIndex skin = -1;
GLTFSkeletonIndex skeleton = -1;
bool joint = false;
+ bool visible = true;
Vector<int> children;
GLTFLightIndex light = -1;
Dictionary additional_data;
@@ -101,6 +102,9 @@ class GLTFNode : public Resource {
GLTFLightIndex get_light();
void set_light(GLTFLightIndex p_light);
+ bool get_visible();
+ void set_visible(bool p_visible);
+
Variant get_additional_data(const StringName &p_extension_name);
bool has_additional_data(const StringName &p_extension_name);
void set_additional_data(const StringName &p_extension_name, Variant p_additional_data);
| diff --git a/modules/gltf/doc_classes/GLTFDocument.xml b/modules/gltf/doc_classes/GLTFDocument.xml
index 47ffc624bad9..46492958a1d2 100644
--- a/modules/gltf/doc_classes/GLTFDocument.xml
+++ b/modules/gltf/doc_classes/GLTFDocument.xml
@@ -126,6 +126,9 @@
How to process the root node during export. See [enum RootNodeMode] for details. The default and recommended value is [constant ROOT_NODE_MODE_SINGLE_ROOT].
[b]Note:[/b] Regardless of how the glTF file is exported, when importing, the root node type and name can be overridden in the scene import settings tab.
+ <member name="visibility_mode" type="int" setter="set_visibility_mode" getter="get_visibility_mode" enum="GLTFDocument.VisibilityMode" default="0">
+ How to deal with node visibility during export. This setting does nothing if all nodes are visible. See [enum VisibilityMode] for details. The default and recommended value is [constant VISIBILITY_MODE_INCLUDE_REQUIRED], which uses the [code]KHR_node_visibility[/code] extension.
</members>
<constants>
<constant name="ROOT_NODE_MODE_SINGLE_ROOT" value="0" enum="RootNodeMode">
@@ -137,5 +140,14 @@
<constant name="ROOT_NODE_MODE_MULTI_ROOT" value="2" enum="RootNodeMode">
Treat the Godot scene's root node as the name of the glTF scene, and add all of its children as root nodes of the glTF file. This uses only vanilla glTF features. This avoids an extra root node, but only the name of the Godot scene's root node will be preserved, as it will not be saved as a node.
</constant>
+ If the scene contains any non-visible nodes, include them, mark them as non-visible with [code]KHR_node_visibility[/code], and require that importers respect their non-visibility. Downside: If the importer does not support [code]KHR_node_visibility[/code], the file cannot be imported.
+ <constant name="VISIBILITY_MODE_INCLUDE_OPTIONAL" value="1" enum="VisibilityMode">
+ If the scene contains any non-visible nodes, include them, mark them as non-visible with [code]KHR_node_visibility[/code], and do not impose any requirements on importers. Downside: If the importer does not support [code]KHR_node_visibility[/code], invisible objects will be visible.
+ <constant name="VISIBILITY_MODE_EXCLUDE" value="2" enum="VisibilityMode">
+ If the scene contains any non-visible nodes, do not include them in the export. This is the same as the behavior in Godot 4.4 and earlier. Downside: Invisible nodes will not exist in the exported file.
</constants>
</class>
diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml
index ed05fde70293..7b09ae91256b 100644
--- a/modules/gltf/doc_classes/GLTFNode.xml
+++ b/modules/gltf/doc_classes/GLTFNode.xml
@@ -83,6 +83,9 @@
<member name="skin" type="int" setter="set_skin" getter="get_skin" default="-1">
If this glTF node has a skin, the index of the [GLTFSkin] in the [GLTFState] that describes the skin's properties. If -1, this node does not have a skin.
+ <member name="visible" type="bool" setter="set_visible" getter="get_visible" default="true">
+ If [code]true[/code], the GLTF node is visible. If [code]false[/code], the GLTF node is not visible. This is translated to the [member Node3D.visible] property in the Godot scene, and is exported to [code]KHR_node_visibility[/code] when [code]false[/code].
<member name="xform" type="Transform3D" setter="set_xform" getter="get_xform" default="Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)">
The transform of the glTF node relative to its parent. This property is usually unused since the position, rotation, and scale properties are preferred.
diff --git a/modules/gltf/editor/editor_scene_exporter_gltf_settings.cpp b/modules/gltf/editor/editor_scene_exporter_gltf_settings.cpp
index 372314578f57..c0dbe4a61eae 100644
--- a/modules/gltf/editor/editor_scene_exporter_gltf_settings.cpp
+++ b/modules/gltf/editor/editor_scene_exporter_gltf_settings.cpp
@@ -50,6 +50,10 @@ bool EditorSceneExporterGLTFSettings::_set(const StringName &p_name, const Varia
_document->set_root_node_mode((GLTFDocument::RootNodeMode)(int64_t)p_value);
+ _document->set_visibility_mode((GLTFDocument::VisibilityMode)(int64_t)p_value);
@@ -70,6 +74,10 @@ bool EditorSceneExporterGLTFSettings::_get(const StringName &p_name, Variant &r_
r_ret = _document->get_root_node_mode();
+ r_ret = _document->get_visibility_mode();
@@ -128,6 +136,21 @@ String get_friendly_config_prefix(Ref<GLTFDocumentExtension> p_extension) {
return "Unknown GLTFDocumentExtension";
+bool is_any_node_invisible(Node *p_node) {
+ if (p_node->has_method("is_visible")) {
+ bool visible = p_node->call("is_visible");
+ if (!visible) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
+ if (is_any_node_invisible(p_node->get_child(i))) {
+ return false;
// Run this before popping up the export settings, because the extensions may have changed.
void EditorSceneExporterGLTFSettings::generate_property_list(Ref<GLTFDocument> p_document, Node *p_root) {
_property_list.clear();
@@ -168,6 +191,11 @@ void EditorSceneExporterGLTFSettings::generate_property_list(Ref<GLTFDocument> p
_property_list.push_back(lossy_quality_prop);
PropertyInfo root_node_mode_prop = PropertyInfo(Variant::INT, "root_node_mode", PROPERTY_HINT_ENUM, "Single Root,Keep Root,Multi Root");
_property_list.push_back(root_node_mode_prop);
+ // If the scene contains any non-visible nodes, show the visibility mode setting.
+ if (p_root != nullptr && is_any_node_invisible(p_root)) {
+ _property_list.push_back(visibility_mode_prop);
String EditorSceneExporterGLTFSettings::get_copyright() const {
diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp
index 7dc7a2bccaeb..5430bffa66c7 100644
--- a/modules/gltf/gltf_document.cpp
+++ b/modules/gltf/gltf_document.cpp
@@ -443,6 +443,17 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> p_state) {
extensions["KHR_lights_punctual"] = lights_punctual;
lights_punctual["light"] = gltf_node->light;
+ if (!gltf_node->visible) {
+ Dictionary khr_node_visibility;
+ extensions["KHR_node_visibility"] = khr_node_visibility;
+ khr_node_visibility["visible"] = gltf_node->visible;
+ p_state->extensions_used.push_back("KHR_node_visibility");
+ if (_visibility_mode == VISIBILITY_MODE_INCLUDE_REQUIRED) {
+ p_state->extensions_required.push_back("KHR_node_visibility");
if (gltf_node->mesh != -1) {
node["mesh"] = gltf_node->mesh;
@@ -637,6 +648,12 @@ Error GLTFDocument::_parse_nodes(Ref<GLTFState> p_state) {
node->light = light;
}
}
+ if (extensions.has("KHR_node_visibility")) {
+ Dictionary khr_node_visibility = extensions["KHR_node_visibility"];
+ if (khr_node_visibility.has("visible")) {
+ node->visible = khr_node_visibility["visible"];
for (Ref<GLTFDocumentExtension> ext : document_extensions) {
ERR_CONTINUE(ext.is_null());
Error err = ext->parse_node_extensions(p_state, node, extensions);
@@ -5844,11 +5861,6 @@ Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> p_state, const GLTFNodeIn
void GLTFDocument::_convert_scene_node(Ref<GLTFState> p_state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) {
- _check_visibility(p_current, retflag);
- if (retflag) {
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint() && p_gltf_root != -1 && p_current->get_owner() == nullptr) {
WARN_VERBOSE("glTF export warning: Node '" + p_current->get_name() + "' has no owner. This is likely a temporary node generated by a @tool script. This would not be saved when saving the Godot scene, therefore it will not be exported to glTF.");
@@ -5857,6 +5869,13 @@ void GLTFDocument::_convert_scene_node(Ref<GLTFState> p_state, Node *p_current,
#endif // TOOLS_ENABLED
Ref<GLTFNode> gltf_node;
gltf_node.instantiate();
+ if (p_current->has_method("is_visible")) {
+ bool visible = p_current->call("is_visible");
+ if (!visible && _visibility_mode == VISIBILITY_MODE_EXCLUDE) {
+ return;
+ gltf_node->visible = visible;
gltf_node->set_original_name(p_current->get_name());
gltf_node->set_name(_gen_unique_name(p_state, p_current->get_name()));
gltf_node->merge_meta_from(p_current);
@@ -5979,19 +5998,6 @@ void GLTFDocument::_convert_csg_shape_to_gltf(CSGShape3D *p_current, GLTFNodeInd
#endif // MODULE_CSG_ENABLED
-void GLTFDocument::_check_visibility(Node *p_node, bool &r_retflag) {
- r_retflag = true;
- Node3D *spatial = Object::cast_to<Node3D>(p_node);
- Node2D *node_2d = Object::cast_to<Node2D>(p_node);
- if (node_2d && !node_2d->is_visible()) {
- if (spatial && !spatial->is_visible()) {
- r_retflag = false;
-}
void GLTFDocument::_convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
ERR_FAIL_NULL(camera);
GLTFCameraIndex camera_index = _convert_camera(p_state, camera);
@@ -6275,6 +6281,7 @@ void GLTFDocument::_generate_scene_node(Ref<GLTFState> p_state, const GLTFNodeIn
if (!gltf_node_name.is_empty()) {
current_node->set_name(gltf_node_name);
+ current_node->set_visible(gltf_node->visible);
// Note: p_scene_parent and p_scene_root must either both be null or both be valid.
if (p_scene_root == nullptr) {
// If the root node argument is null, this is the root node.
@@ -8165,12 +8172,18 @@ void GLTFDocument::_bind_methods() {
BIND_ENUM_CONSTANT(ROOT_NODE_MODE_KEEP_ROOT);
BIND_ENUM_CONSTANT(ROOT_NODE_MODE_MULTI_ROOT);
+ BIND_ENUM_CONSTANT(VISIBILITY_MODE_INCLUDE_REQUIRED);
+ BIND_ENUM_CONSTANT(VISIBILITY_MODE_INCLUDE_OPTIONAL);
+ BIND_ENUM_CONSTANT(VISIBILITY_MODE_EXCLUDE);
ClassDB::bind_method(D_METHOD("set_image_format", "image_format"), &GLTFDocument::set_image_format);
ClassDB::bind_method(D_METHOD("get_image_format"), &GLTFDocument::get_image_format);
ClassDB::bind_method(D_METHOD("set_lossy_quality", "lossy_quality"), &GLTFDocument::set_lossy_quality);
ClassDB::bind_method(D_METHOD("get_lossy_quality"), &GLTFDocument::get_lossy_quality);
ClassDB::bind_method(D_METHOD("set_root_node_mode", "root_node_mode"), &GLTFDocument::set_root_node_mode);
ClassDB::bind_method(D_METHOD("get_root_node_mode"), &GLTFDocument::get_root_node_mode);
+ ClassDB::bind_method(D_METHOD("set_visibility_mode", "visibility_mode"), &GLTFDocument::set_visibility_mode);
+ ClassDB::bind_method(D_METHOD("get_visibility_mode"), &GLTFDocument::get_visibility_mode);
ClassDB::bind_method(D_METHOD("append_from_file", "path", "state", "flags", "base_path"),
&GLTFDocument::append_from_file, DEFVAL(0), DEFVAL(String()));
ClassDB::bind_method(D_METHOD("append_from_buffer", "bytes", "base_path", "state", "flags"),
@@ -8187,6 +8200,7 @@ void GLTFDocument::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING, "image_format"), "set_image_format", "get_image_format");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lossy_quality"), "set_lossy_quality", "get_lossy_quality");
ADD_PROPERTY(PropertyInfo(Variant::INT, "root_node_mode"), "set_root_node_mode", "get_root_node_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_mode"), "set_visibility_mode", "get_visibility_mode");
ClassDB::bind_static_method("GLTFDocument", D_METHOD("import_object_model_property", "state", "json_pointer"), &GLTFDocument::import_object_model_property);
ClassDB::bind_static_method("GLTFDocument", D_METHOD("export_object_model_property", "state", "node_path", "godot_node", "gltf_node_index"), &GLTFDocument::export_object_model_property);
@@ -8257,6 +8271,7 @@ HashSet<String> GLTFDocument::get_supported_gltf_extensions_hashset() {
supported_extensions.insert("KHR_materials_emissive_strength");
supported_extensions.insert("KHR_materials_pbrSpecularGlossiness");
supported_extensions.insert("KHR_materials_unlit");
+ supported_extensions.insert("KHR_node_visibility");
supported_extensions.insert("KHR_texture_transform");
for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
ERR_CONTINUE(ext.is_null());
@@ -8657,6 +8672,14 @@ GLTFDocument::RootNodeMode GLTFDocument::get_root_node_mode() const {
return _root_node_mode;
+void GLTFDocument::set_visibility_mode(VisibilityMode p_visibility_mode) {
+ _visibility_mode = p_visibility_mode;
+GLTFDocument::VisibilityMode GLTFDocument::get_visibility_mode() const {
+ return _visibility_mode;
String GLTFDocument::_gen_unique_name_static(HashSet<String> &r_unique_names, const String &p_name) {
const String s_name = p_name.validate_node_name();
diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h
index 38e668606d8c..0cddb28c23ad 100644
--- a/modules/gltf/gltf_document.h
+++ b/modules/gltf/gltf_document.h
@@ -60,6 +60,11 @@ class GLTFDocument : public Resource {
ROOT_NODE_MODE_KEEP_ROOT,
ROOT_NODE_MODE_MULTI_ROOT,
};
+ VISIBILITY_MODE_INCLUDE_REQUIRED,
+ VISIBILITY_MODE_INCLUDE_OPTIONAL,
+ VISIBILITY_MODE_EXCLUDE,
+ };
int _naming_version = 1;
@@ -67,6 +72,7 @@ class GLTFDocument : public Resource {
float _lossy_quality = 0.75f;
Ref<GLTFDocumentExtension> _image_save_extension;
RootNodeMode _root_node_mode = RootNodeMode::ROOT_NODE_MODE_SINGLE_ROOT;
+ VisibilityMode _visibility_mode = VisibilityMode::VISIBILITY_MODE_INCLUDE_REQUIRED;
protected:
static void _bind_methods();
@@ -94,6 +100,8 @@ class GLTFDocument : public Resource {
float get_lossy_quality() const;
void set_root_node_mode(RootNodeMode p_root_node_mode);
RootNodeMode get_root_node_mode() const;
+ void set_visibility_mode(VisibilityMode p_visibility_mode);
+ VisibilityMode get_visibility_mode() const;
static String _gen_unique_name_static(HashSet<String> &r_unique_names, const String &p_name);
@@ -378,3 +386,4 @@ class GLTFDocument : public Resource {
};
VARIANT_ENUM_CAST(GLTFDocument::RootNodeMode);
diff --git a/modules/gltf/structures/gltf_node.cpp b/modules/gltf/structures/gltf_node.cpp
index 1626313551ef..8a42ae3e8d86 100644
--- a/modules/gltf/structures/gltf_node.cpp
+++ b/modules/gltf/structures/gltf_node.cpp
@@ -60,6 +60,8 @@ void GLTFNode::_bind_methods() {
ClassDB::bind_method(D_METHOD("append_child_index", "child_index"), &GLTFNode::append_child_index);
ClassDB::bind_method(D_METHOD("get_light"), &GLTFNode::get_light);
ClassDB::bind_method(D_METHOD("set_light", "light"), &GLTFNode::set_light);
+ ClassDB::bind_method(D_METHOD("get_visible"), &GLTFNode::get_visible);
+ ClassDB::bind_method(D_METHOD("set_visible", "visible"), &GLTFNode::set_visible);
ClassDB::bind_method(D_METHOD("get_additional_data", "extension_name"), &GLTFNode::get_additional_data);
ClassDB::bind_method(D_METHOD("set_additional_data", "extension_name", "additional_data"), &GLTFNode::set_additional_data);
ClassDB::bind_method(D_METHOD("get_scene_node_path", "gltf_state", "handle_skeletons"), &GLTFNode::get_scene_node_path, DEFVAL(true));
@@ -77,6 +79,7 @@ void GLTFNode::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale"), "set_scale", "get_scale"); // Vector3
ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "children"), "set_children", "get_children"); // Vector<int>
ADD_PROPERTY(PropertyInfo(Variant::INT, "light"), "set_light", "get_light"); // GLTFLightIndex
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "get_visible"); // bool
String GLTFNode::get_original_name() {
@@ -186,6 +189,14 @@ void GLTFNode::set_light(GLTFLightIndex p_light) {
light = p_light;
+bool GLTFNode::get_visible() {
+ return visible;
+void GLTFNode::set_visible(bool p_visible) {
+ visible = p_visible;
Variant GLTFNode::get_additional_data(const StringName &p_extension_name) {
return additional_data[p_extension_name];
diff --git a/modules/gltf/structures/gltf_node.h b/modules/gltf/structures/gltf_node.h
index b0f75eea3bd3..41235de7366a 100644
--- a/modules/gltf/structures/gltf_node.h
+++ b/modules/gltf/structures/gltf_node.h
@@ -50,6 +50,7 @@ class GLTFNode : public Resource {
GLTFSkinIndex skin = -1;
GLTFSkeletonIndex skeleton = -1;
bool joint = false;
Vector<int> children;
GLTFLightIndex light = -1;
Dictionary additional_data;
@@ -101,6 +102,9 @@ class GLTFNode : public Resource {
GLTFLightIndex get_light();
void set_light(GLTFLightIndex p_light);
+ bool get_visible();
+ void set_visible(bool p_visible);
Variant get_additional_data(const StringName &p_extension_name);
bool has_additional_data(const StringName &p_extension_name);
void set_additional_data(const StringName &p_extension_name, Variant p_additional_data); | [
"+\t\t<constant name=\"VISIBILITY_MODE_INCLUDE_REQUIRED\" value=\"0\" enum=\"VisibilityMode\">",
"+\t\tPropertyInfo visibility_mode_prop = PropertyInfo(Variant::INT, \"visibility_mode\", PROPERTY_HINT_ENUM, \"Include & Required,Include & Optional,Exclude\");",
"+\t\t\tif (!p_state->extensions_used.has(\"KHR_node_visibility\")) {",
"-\tbool retflag = true;",
"-",
"+\tenum VisibilityMode {",
"+VARIANT_ENUM_CAST(GLTFDocument::VisibilityMode);",
"+\tbool visible = true;"
] | [
18,
97,
115,
142,
180,
250,
279,
324
] | {
"additions": 108,
"author": "aaronfranke",
"deletions": 18,
"html_url": "https://github.com/godotengine/godot/pull/93722",
"issue_id": 93722,
"merged_at": "2025-04-24T22:23:37Z",
"omission_probability": 0.1,
"pr_number": 93722,
"repo": "godotengine/godot",
"title": "Implement `KHR_node_visibility` in the GLTF module",
"total_changes": 126
} |
708 | diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp
index 16a7578d8acd..2f960beccac9 100644
--- a/editor/editor_file_system.cpp
+++ b/editor/editor_file_system.cpp
@@ -3437,7 +3437,7 @@ Error EditorFileSystem::make_dir_recursive(const String &p_path, const String &p
ERR_FAIL_NULL_V(parent, ERR_FILE_NOT_FOUND);
folders_to_sort.insert(parent->get_instance_id());
- const PackedStringArray folders = p_path.trim_prefix(path).trim_suffix("/").split("/");
+ const PackedStringArray folders = p_path.trim_prefix(path).split("/", false);
for (const String &folder : folders) {
const int current = parent->find_dir_index(folder);
if (current > -1) {
diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp
index 67c9f0dba2ba..e7c49b2a874c 100644
--- a/editor/filesystem_dock.cpp
+++ b/editor/filesystem_dock.cpp
@@ -2743,7 +2743,13 @@ void FileSystemDock::focus_on_filter() {
}
void FileSystemDock::create_directory(const String &p_path, const String &p_base_dir) {
- Error err = EditorFileSystem::get_singleton()->make_dir_recursive(p_path.trim_prefix(p_base_dir), p_base_dir);
+ String trimmed_path = p_path;
+ if (!p_base_dir.is_empty()) {
+ // Trims off the joining '/' if the base didn't end with one. If the base did have it
+ // and there's two slashes, the empty directory is safe to trim off anyways.
+ trimmed_path = trimmed_path.trim_prefix(p_base_dir).trim_prefix("/");
+ }
+ Error err = EditorFileSystem::get_singleton()->make_dir_recursive(trimmed_path, p_base_dir);
if (err != OK) {
EditorNode::get_singleton()->show_warning(vformat(TTR("Could not create folder: %s"), error_names[err]));
}
| diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp
index 16a7578d8acd..2f960beccac9 100644
--- a/editor/editor_file_system.cpp
+++ b/editor/editor_file_system.cpp
@@ -3437,7 +3437,7 @@ Error EditorFileSystem::make_dir_recursive(const String &p_path, const String &p
ERR_FAIL_NULL_V(parent, ERR_FILE_NOT_FOUND);
folders_to_sort.insert(parent->get_instance_id());
- const PackedStringArray folders = p_path.trim_prefix(path).trim_suffix("/").split("/");
for (const String &folder : folders) {
const int current = parent->find_dir_index(folder);
if (current > -1) {
diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp
index 67c9f0dba2ba..e7c49b2a874c 100644
--- a/editor/filesystem_dock.cpp
+++ b/editor/filesystem_dock.cpp
@@ -2743,7 +2743,13 @@ void FileSystemDock::focus_on_filter() {
}
void FileSystemDock::create_directory(const String &p_path, const String &p_base_dir) {
- Error err = EditorFileSystem::get_singleton()->make_dir_recursive(p_path.trim_prefix(p_base_dir), p_base_dir);
+ String trimmed_path = p_path;
+ if (!p_base_dir.is_empty()) {
+ // Trims off the joining '/' if the base didn't end with one. If the base did have it
+ // and there's two slashes, the empty directory is safe to trim off anyways.
+ trimmed_path = trimmed_path.trim_prefix(p_base_dir).trim_prefix("/");
+ }
+ Error err = EditorFileSystem::get_singleton()->make_dir_recursive(trimmed_path, p_base_dir);
if (err != OK) {
EditorNode::get_singleton()->show_warning(vformat(TTR("Could not create folder: %s"), error_names[err]));
} | [
"+\tconst PackedStringArray folders = p_path.trim_prefix(path).split(\"/\", false);"
] | [
9
] | {
"additions": 8,
"author": "precup",
"deletions": 2,
"html_url": "https://github.com/godotengine/godot/pull/104022",
"issue_id": 104022,
"merged_at": "2025-03-19T11:37:52Z",
"omission_probability": 0.1,
"pr_number": 104022,
"repo": "godotengine/godot",
"title": "Defend against directories without trailing slashes",
"total_changes": 10
} |
709 | diff --git a/scene/main/window.cpp b/scene/main/window.cpp
index c145ddc6aa09..27afd864adb4 100644
--- a/scene/main/window.cpp
+++ b/scene/main/window.cpp
@@ -236,15 +236,15 @@ void Window::_get_property_list(List<PropertyInfo> *p_list) const {
}
void Window::_validate_property(PropertyInfo &p_property) const {
- if (p_property.name == "position" && initial_position != WINDOW_INITIAL_POSITION_ABSOLUTE) {
- p_property.usage = PROPERTY_USAGE_NONE;
- }
-
- if (p_property.name == "current_screen" && initial_position != WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN) {
- p_property.usage = PROPERTY_USAGE_NONE;
- }
-
- if (p_property.name == "theme_type_variation") {
+ if (p_property.name == "position") {
+ if (initial_position != WINDOW_INITIAL_POSITION_ABSOLUTE) {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
+ } else if (p_property.name == "current_screen") {
+ if (initial_position != WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN) {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
+ } else if (p_property.name == "theme_type_variation") {
List<StringName> names;
// Only the default theme and the project theme are used for the list of options.
| diff --git a/scene/main/window.cpp b/scene/main/window.cpp
index c145ddc6aa09..27afd864adb4 100644
--- a/scene/main/window.cpp
+++ b/scene/main/window.cpp
@@ -236,15 +236,15 @@ void Window::_get_property_list(List<PropertyInfo> *p_list) const {
}
void Window::_validate_property(PropertyInfo &p_property) const {
- if (p_property.name == "position" && initial_position != WINDOW_INITIAL_POSITION_ABSOLUTE) {
- if (p_property.name == "current_screen" && initial_position != WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN) {
+ if (p_property.name == "position") {
+ } else if (p_property.name == "current_screen") {
+ if (initial_position != WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN) {
List<StringName> names;
// Only the default theme and the project theme are used for the list of options. | [
"-\tif (p_property.name == \"theme_type_variation\") {",
"+\t\tif (initial_position != WINDOW_INITIAL_POSITION_ABSOLUTE) {",
"+\t} else if (p_property.name == \"theme_type_variation\") {"
] | [
16,
18,
25
] | {
"additions": 9,
"author": "KoBeWi",
"deletions": 9,
"html_url": "https://github.com/godotengine/godot/pull/105730",
"issue_id": 105730,
"merged_at": "2025-04-24T22:23:36Z",
"omission_probability": 0.1,
"pr_number": 105730,
"repo": "godotengine/godot",
"title": "Improve Window's `_validate_property()`",
"total_changes": 18
} |
710 | diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp
index 0c1d2f40a0dd..2b415c923d91 100644
--- a/scene/resources/animation.cpp
+++ b/scene/resources/animation.cpp
@@ -4105,7 +4105,7 @@ void Animation::clear() {
emit_changed();
}
-bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error) {
+bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error, bool p_is_nearest) {
// Remove overlapping keys.
if (Math::is_equal_approx(t0.time, t1.time) || Math::is_equal_approx(t1.time, t2.time)) {
return true;
@@ -4113,6 +4113,9 @@ bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float
if (abs(t0.value - t1.value) < p_allowed_precision_error && abs(t1.value - t2.value) < p_allowed_precision_error) {
return true;
}
+ if (p_is_nearest) {
+ return false;
+ }
// Calc velocities.
double v0 = (t1.value - t0.value) / (t1.time - t0.time);
double v1 = (t2.value - t1.value) / (t2.time - t1.time);
@@ -4133,7 +4136,7 @@ bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float
return false;
}
-bool Animation::_vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error) {
+bool Animation::_vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest) {
// Remove overlapping keys.
if (Math::is_equal_approx(t0.time, t1.time) || Math::is_equal_approx(t1.time, t2.time)) {
return true;
@@ -4141,6 +4144,9 @@ bool Animation::_vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<V
if ((t0.value - t1.value).length() < p_allowed_precision_error && (t1.value - t2.value).length() < p_allowed_precision_error) {
return true;
}
+ if (p_is_nearest) {
+ return false;
+ }
// Calc velocities.
Vector2 vc0 = (t1.value - t0.value) / (t1.time - t0.time);
Vector2 vc1 = (t2.value - t1.value) / (t2.time - t1.time);
@@ -4164,7 +4170,7 @@ bool Animation::_vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<V
return false;
}
-bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error) {
+bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest) {
// Remove overlapping keys.
if (Math::is_equal_approx(t0.time, t1.time) || Math::is_equal_approx(t1.time, t2.time)) {
return true;
@@ -4172,6 +4178,10 @@ bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<V
if ((t0.value - t1.value).length() < p_allowed_precision_error && (t1.value - t2.value).length() < p_allowed_precision_error) {
return true;
}
+ if (p_is_nearest) {
+ return false;
+ }
+
// Calc velocities.
Vector3 vc0 = (t1.value - t0.value) / (t1.time - t0.time);
Vector3 vc1 = (t2.value - t1.value) / (t2.time - t1.time);
@@ -4195,7 +4205,7 @@ bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<V
return false;
}
-bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error) {
+bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest) {
// Remove overlapping keys.
if (Math::is_equal_approx(t0.time, t1.time) || Math::is_equal_approx(t1.time, t2.time)) {
return true;
@@ -4203,6 +4213,9 @@ bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const
if ((t0.value - t1.value).length() < p_allowed_precision_error && (t1.value - t2.value).length() < p_allowed_precision_error) {
return true;
}
+ if (p_is_nearest) {
+ return false;
+ }
// Check axis.
Quaternion q0 = t0.value * t1.value * t0.value.inverse();
Quaternion q1 = t1.value * t2.value * t1.value.inverse();
@@ -4232,15 +4245,19 @@ bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const
void Animation::_position_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_POSITION_3D);
+ bool is_nearest = false;
+ if (tracks[p_idx]->interpolation == INTERPOLATION_NEAREST) {
+ is_nearest = true;
+ } else if (tracks[p_idx]->interpolation != INTERPOLATION_LINEAR) {
+ return;
+ }
PositionTrack *tt = static_cast<PositionTrack *>(tracks[p_idx]);
-
int i = 0;
while (i < tt->positions.size() - 2) {
TKey<Vector3> t0 = tt->positions[i];
TKey<Vector3> t1 = tt->positions[i + 1];
TKey<Vector3> t2 = tt->positions[i + 2];
-
- bool erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ bool erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
if (erase) {
tt->positions.remove_at(i + 1);
} else {
@@ -4258,15 +4275,19 @@ void Animation::_position_track_optimize(int p_idx, real_t p_allowed_velocity_er
void Animation::_rotation_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_ROTATION_3D);
+ bool is_nearest = false;
+ if (tracks[p_idx]->interpolation == INTERPOLATION_NEAREST) {
+ is_nearest = true;
+ } else if (tracks[p_idx]->interpolation != INTERPOLATION_LINEAR) {
+ return;
+ }
RotationTrack *rt = static_cast<RotationTrack *>(tracks[p_idx]);
-
int i = 0;
while (i < rt->rotations.size() - 2) {
TKey<Quaternion> t0 = rt->rotations[i];
TKey<Quaternion> t1 = rt->rotations[i + 1];
TKey<Quaternion> t2 = rt->rotations[i + 2];
-
- bool erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ bool erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
if (erase) {
rt->rotations.remove_at(i + 1);
} else {
@@ -4284,15 +4305,19 @@ void Animation::_rotation_track_optimize(int p_idx, real_t p_allowed_velocity_er
void Animation::_scale_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_SCALE_3D);
+ bool is_nearest = false;
+ if (tracks[p_idx]->interpolation == INTERPOLATION_NEAREST) {
+ is_nearest = true;
+ } else if (tracks[p_idx]->interpolation != INTERPOLATION_LINEAR) {
+ return;
+ }
ScaleTrack *st = static_cast<ScaleTrack *>(tracks[p_idx]);
-
int i = 0;
while (i < st->scales.size() - 2) {
TKey<Vector3> t0 = st->scales[i];
TKey<Vector3> t1 = st->scales[i + 1];
TKey<Vector3> t2 = st->scales[i + 2];
-
- bool erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ bool erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
if (erase) {
st->scales.remove_at(i + 1);
} else {
@@ -4310,15 +4335,20 @@ void Animation::_scale_track_optimize(int p_idx, real_t p_allowed_velocity_err,
void Animation::_blend_shape_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_BLEND_SHAPE);
+ bool is_nearest = false;
+ if (tracks[p_idx]->interpolation == INTERPOLATION_NEAREST) {
+ is_nearest = true;
+ } else if (tracks[p_idx]->interpolation != INTERPOLATION_LINEAR) {
+ return;
+ }
BlendShapeTrack *bst = static_cast<BlendShapeTrack *>(tracks[p_idx]);
-
int i = 0;
while (i < bst->blend_shapes.size() - 2) {
TKey<float> t0 = bst->blend_shapes[i];
TKey<float> t1 = bst->blend_shapes[i + 1];
TKey<float> t2 = bst->blend_shapes[i + 2];
- bool erase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error);
+ bool erase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error, is_nearest);
if (erase) {
bst->blend_shapes.remove_at(i + 1);
} else {
@@ -4336,6 +4366,12 @@ void Animation::_blend_shape_track_optimize(int p_idx, real_t p_allowed_velocity
void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_INDEX(p_idx, tracks.size());
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_VALUE);
+ bool is_nearest = false;
+ if (tracks[p_idx]->interpolation == INTERPOLATION_NEAREST) {
+ is_nearest = true;
+ } else if (tracks[p_idx]->interpolation != INTERPOLATION_LINEAR && tracks[p_idx]->interpolation != INTERPOLATION_LINEAR_ANGLE) {
+ return;
+ }
ValueTrack *vt = static_cast<ValueTrack *>(tracks[p_idx]);
if (vt->values.is_empty()) {
return;
@@ -4367,7 +4403,7 @@ void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err,
break; // Rotation is more than 180 deg, keep key.
}
}
- erase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error);
+ erase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error, is_nearest);
} break;
case Variant::VECTOR2: {
TKey<Vector2> t0;
@@ -4379,7 +4415,7 @@ void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err,
t0.value = vt->values[i].value;
t1.value = vt->values[i + 1].value;
t2.value = vt->values[i + 2].value;
- erase = _vector2_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ erase = _vector2_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
} break;
case Variant::VECTOR3: {
TKey<Vector3> t0;
@@ -4391,7 +4427,7 @@ void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err,
t0.value = vt->values[i].value;
t1.value = vt->values[i + 1].value;
t2.value = vt->values[i + 2].value;
- erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
} break;
case Variant::QUATERNION: {
TKey<Quaternion> t0;
@@ -4403,7 +4439,7 @@ void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err,
t0.value = vt->values[i].value;
t1.value = vt->values[i + 1].value;
t2.value = vt->values[i + 2].value;
- erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
} break;
default: {
} break;
diff --git a/scene/resources/animation.h b/scene/resources/animation.h
index bc6f48bfeaa6..6cf432627904 100644
--- a/scene/resources/animation.h
+++ b/scene/resources/animation.h
@@ -373,10 +373,10 @@ class Animation : public Resource {
// bind helpers
private:
- bool _float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error);
- bool _vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
- bool _vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
- bool _quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
+ bool _float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error, bool p_is_nearest);
+ bool _vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest);
+ bool _vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest);
+ bool _quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest);
void _position_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error);
void _rotation_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
| diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp
index 0c1d2f40a0dd..2b415c923d91 100644
--- a/scene/resources/animation.cpp
+++ b/scene/resources/animation.cpp
@@ -4105,7 +4105,7 @@ void Animation::clear() {
emit_changed();
-bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error) {
+bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error, bool p_is_nearest) {
@@ -4113,6 +4113,9 @@ bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float
if (abs(t0.value - t1.value) < p_allowed_precision_error && abs(t1.value - t2.value) < p_allowed_precision_error) {
double v0 = (t1.value - t0.value) / (t1.time - t0.time);
double v1 = (t2.value - t1.value) / (t2.time - t1.time);
@@ -4133,7 +4136,7 @@ bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float
-bool Animation::_vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error) {
+bool Animation::_vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest) {
@@ -4141,6 +4144,9 @@ bool Animation::_vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<V
Vector2 vc0 = (t1.value - t0.value) / (t1.time - t0.time);
Vector2 vc1 = (t2.value - t1.value) / (t2.time - t1.time);
@@ -4164,7 +4170,7 @@ bool Animation::_vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<V
-bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error) {
+bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest) {
@@ -4172,6 +4178,10 @@ bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<V
+
Vector3 vc0 = (t1.value - t0.value) / (t1.time - t0.time);
Vector3 vc1 = (t2.value - t1.value) / (t2.time - t1.time);
@@ -4195,7 +4205,7 @@ bool Animation::_vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<V
-bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error) {
+bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest) {
@@ -4203,6 +4213,9 @@ bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const
// Check axis.
Quaternion q0 = t0.value * t1.value * t0.value.inverse();
Quaternion q1 = t1.value * t2.value * t1.value.inverse();
@@ -4232,15 +4245,19 @@ bool Animation::_quaternion_track_optimize_key(const TKey<Quaternion> t0, const
void Animation::_position_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_POSITION_3D);
PositionTrack *tt = static_cast<PositionTrack *>(tracks[p_idx]);
while (i < tt->positions.size() - 2) {
TKey<Vector3> t0 = tt->positions[i];
TKey<Vector3> t1 = tt->positions[i + 1];
TKey<Vector3> t2 = tt->positions[i + 2];
tt->positions.remove_at(i + 1);
@@ -4258,15 +4275,19 @@ void Animation::_position_track_optimize(int p_idx, real_t p_allowed_velocity_er
void Animation::_rotation_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_ROTATION_3D);
RotationTrack *rt = static_cast<RotationTrack *>(tracks[p_idx]);
while (i < rt->rotations.size() - 2) {
TKey<Quaternion> t0 = rt->rotations[i];
TKey<Quaternion> t1 = rt->rotations[i + 1];
TKey<Quaternion> t2 = rt->rotations[i + 2];
- bool erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ bool erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
rt->rotations.remove_at(i + 1);
@@ -4284,15 +4305,19 @@ void Animation::_rotation_track_optimize(int p_idx, real_t p_allowed_velocity_er
void Animation::_scale_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_SCALE_3D);
ScaleTrack *st = static_cast<ScaleTrack *>(tracks[p_idx]);
while (i < st->scales.size() - 2) {
TKey<Vector3> t0 = st->scales[i];
TKey<Vector3> t1 = st->scales[i + 1];
TKey<Vector3> t2 = st->scales[i + 2];
st->scales.remove_at(i + 1);
@@ -4310,15 +4335,20 @@ void Animation::_scale_track_optimize(int p_idx, real_t p_allowed_velocity_err,
void Animation::_blend_shape_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_precision_error) {
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_BLEND_SHAPE);
BlendShapeTrack *bst = static_cast<BlendShapeTrack *>(tracks[p_idx]);
while (i < bst->blend_shapes.size() - 2) {
TKey<float> t0 = bst->blend_shapes[i];
TKey<float> t1 = bst->blend_shapes[i + 1];
TKey<float> t2 = bst->blend_shapes[i + 2];
- bool erase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error);
+ bool erase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error, is_nearest);
bst->blend_shapes.remove_at(i + 1);
@@ -4336,6 +4366,12 @@ void Animation::_blend_shape_track_optimize(int p_idx, real_t p_allowed_velocity
void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error) {
ERR_FAIL_COND(tracks[p_idx]->type != TYPE_VALUE);
+ } else if (tracks[p_idx]->interpolation != INTERPOLATION_LINEAR && tracks[p_idx]->interpolation != INTERPOLATION_LINEAR_ANGLE) {
ValueTrack *vt = static_cast<ValueTrack *>(tracks[p_idx]);
if (vt->values.is_empty()) {
return;
@@ -4367,7 +4403,7 @@ void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err,
break; // Rotation is more than 180 deg, keep key.
}
}
case Variant::VECTOR2: {
TKey<Vector2> t0;
@@ -4379,7 +4415,7 @@ void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err,
- erase = _vector2_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ erase = _vector2_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
case Variant::VECTOR3: {
TKey<Vector3> t0;
@@ -4391,7 +4427,7 @@ void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err,
- erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ erase = _vector3_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
case Variant::QUATERNION: {
TKey<Quaternion> t0;
@@ -4403,7 +4439,7 @@ void Animation::_value_track_optimize(int p_idx, real_t p_allowed_velocity_err,
- erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error);
+ erase = _quaternion_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_angular_err, p_allowed_precision_error, is_nearest);
default: {
diff --git a/scene/resources/animation.h b/scene/resources/animation.h
index bc6f48bfeaa6..6cf432627904 100644
--- a/scene/resources/animation.h
+++ b/scene/resources/animation.h
@@ -373,10 +373,10 @@ class Animation : public Resource {
// bind helpers
private:
- bool _float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error);
- bool _vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
- bool _vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
- bool _quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
+ bool _vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest);
+ bool _vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest);
+ bool _quaternion_track_optimize_key(const TKey<Quaternion> t0, const TKey<Quaternion> t1, const TKey<Quaternion> t2, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error, bool p_is_nearest);
void _position_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_err, real_t p_allowed_precision_error);
void _rotation_track_optimize(int p_idx, real_t p_allowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error); | [
"-\t\t\t\terase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error);",
"+\t\t\t\terase = _float_track_optimize_key(t0, t1, t2, p_allowed_velocity_err, p_allowed_precision_error, is_nearest);",
"+\tbool _float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error, bool p_is_nearest);"
] | [
190,
191,
234
] | {
"additions": 59,
"author": "lazarosY",
"deletions": 23,
"html_url": "https://github.com/godotengine/godot/pull/105644",
"issue_id": 105644,
"merged_at": "2025-04-24T22:23:37Z",
"omission_probability": 0.1,
"pr_number": 105644,
"repo": "godotengine/godot",
"title": "Fix the Animation Optimization results for Nearest and Cubic Interpolation",
"total_changes": 82
} |
711 | diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp
index 565a97342571..6c0d24a2b000 100644
--- a/core/config/project_settings.cpp
+++ b/core/config/project_settings.cpp
@@ -422,6 +422,7 @@ void ProjectSettings::_get_property_list(List<PropertyInfo> *p_list) const {
_THREAD_SAFE_METHOD_
RBSet<_VCSort> vclist;
+ HashMap<String, Vector<_VCSort>> setting_overrides;
for (const KeyValue<StringName, VariantContainer> &E : props) {
const VariantContainer *v = &E.value;
@@ -462,23 +463,41 @@ void ProjectSettings::_get_property_list(List<PropertyInfo> *p_list) const {
if (v->restart_if_changed) {
vc.flags |= PROPERTY_USAGE_RESTART_IF_CHANGED;
}
- vclist.insert(vc);
- }
- for (const _VCSort &E : vclist) {
- String prop_info_name = E.name;
- int dot = prop_info_name.find_char('.');
- if (dot != -1 && !custom_prop_info.has(prop_info_name)) {
- prop_info_name = prop_info_name.substr(0, dot);
+ int dot = vc.name.rfind_char('.');
+ if (dot != -1 && !custom_prop_info.has(vc.name)) {
+ StringName n = vc.name.substr(0, dot);
+ if (props.has(n)) { // Property is an override.
+ setting_overrides[n].append(vc);
+ } else {
+ vclist.insert(vc);
+ }
+ } else {
+ vclist.insert(vc);
}
+ }
- if (custom_prop_info.has(prop_info_name)) {
- PropertyInfo pi = custom_prop_info[prop_info_name];
- pi.name = E.name;
- pi.usage = E.flags;
+ for (const _VCSort &base : vclist) {
+ if (custom_prop_info.has(base.name)) {
+ PropertyInfo pi = custom_prop_info[base.name];
+ pi.name = base.name;
+ pi.usage = base.flags;
p_list->push_back(pi);
} else {
- p_list->push_back(PropertyInfo(E.type, E.name, PROPERTY_HINT_NONE, "", E.flags));
+ p_list->push_back(PropertyInfo(base.type, base.name, PROPERTY_HINT_NONE, "", base.flags));
+ }
+
+ if (setting_overrides.has(base.name)) {
+ for (const _VCSort &over : setting_overrides.get(base.name)) {
+ if (custom_prop_info.has(over.name)) {
+ PropertyInfo pi = custom_prop_info[over.name];
+ pi.name = over.name;
+ pi.usage = over.flags;
+ p_list->push_back(pi);
+ } else {
+ p_list->push_back(PropertyInfo(over.type, over.name, PROPERTY_HINT_NONE, "", over.flags));
+ }
+ }
}
}
}
| diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp
index 565a97342571..6c0d24a2b000 100644
--- a/core/config/project_settings.cpp
+++ b/core/config/project_settings.cpp
@@ -422,6 +422,7 @@ void ProjectSettings::_get_property_list(List<PropertyInfo> *p_list) const {
_THREAD_SAFE_METHOD_
RBSet<_VCSort> vclist;
+ HashMap<String, Vector<_VCSort>> setting_overrides;
for (const KeyValue<StringName, VariantContainer> &E : props) {
const VariantContainer *v = &E.value;
@@ -462,23 +463,41 @@ void ProjectSettings::_get_property_list(List<PropertyInfo> *p_list) const {
if (v->restart_if_changed) {
vc.flags |= PROPERTY_USAGE_RESTART_IF_CHANGED;
- vclist.insert(vc);
- }
- for (const _VCSort &E : vclist) {
- String prop_info_name = E.name;
- int dot = prop_info_name.find_char('.');
- if (dot != -1 && !custom_prop_info.has(prop_info_name)) {
- prop_info_name = prop_info_name.substr(0, dot);
+ int dot = vc.name.rfind_char('.');
+ if (dot != -1 && !custom_prop_info.has(vc.name)) {
+ StringName n = vc.name.substr(0, dot);
+ setting_overrides[n].append(vc);
+ } else {
+ vclist.insert(vc);
+ } else {
+ vclist.insert(vc);
+ }
- if (custom_prop_info.has(prop_info_name)) {
- PropertyInfo pi = custom_prop_info[prop_info_name];
- pi.name = E.name;
- pi.usage = E.flags;
+ for (const _VCSort &base : vclist) {
+ if (custom_prop_info.has(base.name)) {
+ PropertyInfo pi = custom_prop_info[base.name];
+ pi.name = base.name;
+ pi.usage = base.flags;
p_list->push_back(pi);
} else {
- p_list->push_back(PropertyInfo(E.type, E.name, PROPERTY_HINT_NONE, "", E.flags));
+ p_list->push_back(PropertyInfo(base.type, base.name, PROPERTY_HINT_NONE, "", base.flags));
+ }
+
+ for (const _VCSort &over : setting_overrides.get(base.name)) {
+ if (custom_prop_info.has(over.name)) {
+ PropertyInfo pi = custom_prop_info[over.name];
+ pi.name = over.name;
+ pi.usage = over.flags;
+ p_list->push_back(pi);
+ } else {
+ p_list->push_back(PropertyInfo(over.type, over.name, PROPERTY_HINT_NONE, "", over.flags));
+ }
}
} | [
"+\t\t\tif (props.has(n)) { // Property is an override.",
"+\t\tif (setting_overrides.has(base.name)) {"
] | [
27,
52
] | {
"additions": 31,
"author": "dugramen",
"deletions": 12,
"html_url": "https://github.com/godotengine/godot/pull/103336",
"issue_id": 103336,
"merged_at": "2025-04-24T22:23:37Z",
"omission_probability": 0.1,
"pr_number": 103336,
"repo": "godotengine/godot",
"title": "Keep ProjectSettings overrides right below the original setting",
"total_changes": 43
} |
712 | diff --git a/.github/workflows/windows_builds.yml b/.github/workflows/windows_builds.yml
index 95e3d4a553d1..384284b6047e 100644
--- a/.github/workflows/windows_builds.yml
+++ b/.github/workflows/windows_builds.yml
@@ -30,7 +30,7 @@ jobs:
# Skip debug symbols, they're way too big with MSVC.
sconsflags: debug_symbols=no vsproj=yes vsproj_gen_only=no windows_subsystem=console
bin: ./bin/godot.windows.editor.x86_64.exe
- artifact: true
+ compiler: msvc
- name: Editor w/ clang-cl (target=editor, tests=yes, use_llvm=yes)
cache-name: windows-editor-clang
@@ -38,6 +38,7 @@ jobs:
tests: true
sconsflags: debug_symbols=no windows_subsystem=console use_llvm=yes
bin: ./bin/godot.windows.editor.x86_64.llvm.exe
+ compiler: clang
- name: Template (target=template_release, tests=yes)
cache-name: windows-template
@@ -45,7 +46,16 @@ jobs:
tests: true
sconsflags: debug_symbols=no
bin: ./bin/godot.windows.template_release.x86_64.console.exe
- artifact: true
+ compiler: msvc
+
+ - name: Template w/ GCC (target=template_release, tests=yes, use_mingw=yes)
+ cache-name: windows-template-gcc
+ # MinGW takes MUCH longer to compile; save time by only targeting Template.
+ target: template_release
+ tests: true
+ sconsflags: debug_symbols=no use_mingw=yes
+ bin: ./bin/godot.windows.template_release.x86_64.console.exe
+ compiler: gcc
steps:
- name: Checkout
@@ -69,16 +79,21 @@ jobs:
uses: dsaltares/[email protected]
with:
repo: godotengine/godot-angle-static
- version: tags/chromium/6029
- file: Windows.6029-1.MSVC_17.x86_64.x86_32.zip
+ version: tags/chromium/6601.2
+ file: godot-angle-static-x86_64-${{ matrix.compiler == 'gcc' && 'gcc' || 'msvc' }}-release.zip
target: angle/angle.zip
- name: Extract pre-built ANGLE static libraries
run: Expand-Archive -Force angle/angle.zip ${{ github.workspace }}/
- name: Setup MSVC problem matcher
+ if: matrix.compiler == 'msvc'
uses: ammaraskar/msvc-problem-matcher@master
+ - name: Setup GCC problem matcher
+ if: matrix.compiler != 'msvc'
+ uses: ammaraskar/gcc-problem-matcher@master
+
- name: Compilation
uses: ./.github/actions/godot-build
with:
@@ -94,12 +109,12 @@ jobs:
continue-on-error: true
- name: Prepare artifact
- if: ${{ matrix.artifact }}
+ if: matrix.compiler == 'msvc'
run: |
Remove-Item bin/* -Include *.exp,*.lib,*.pdb -Force
- name: Upload artifact
- if: ${{ matrix.artifact }}
+ if: matrix.compiler == 'msvc'
uses: ./.github/actions/upload-artifact
with:
name: ${{ matrix.cache-name }}
diff --git a/drivers/d3d12/SCsub b/drivers/d3d12/SCsub
index b6ceed23ac83..beeb13398e37 100644
--- a/drivers/d3d12/SCsub
+++ b/drivers/d3d12/SCsub
@@ -4,6 +4,8 @@ from misc.utility.scons_hints import *
import os
from pathlib import Path
+import methods
+
Import("env")
env_d3d12_rdd = env.Clone()
@@ -139,6 +141,10 @@ else:
extra_defines += [
"HAVE_STRUCT_TIMESPEC",
]
+ if methods.using_gcc(env) and methods.get_compiler_version(env)["major"] < 13:
+ # `region` & `endregion` not recognized as valid pragmas.
+ env_d3d12_rdd.Append(CCFLAGS=["-Wno-unknown-pragmas"])
+ env.Append(CCFLAGS=["-Wno-unknown-pragmas"])
# This is needed since rendering_device_d3d12.cpp needs to include some Mesa internals.
env_d3d12_rdd.Prepend(CPPPATH=mesa_private_inc_paths)
diff --git a/drivers/d3d12/dxil_hash.cpp b/drivers/d3d12/dxil_hash.cpp
index f94a4a30df3c..e08492c9ea9f 100644
--- a/drivers/d3d12/dxil_hash.cpp
+++ b/drivers/d3d12/dxil_hash.cpp
@@ -96,7 +96,7 @@ void compute_dxil_hash(const BYTE *pData, UINT byteCount, BYTE *pOutHash) {
UINT NextEndState = bTwoRowsPadding ? N - 2 : N - 1;
const BYTE *pCurrData = pData;
for (UINT i = 0; i < N; i++, offset += 64, pCurrData += 64) {
- UINT x[16];
+ UINT x[16] = {};
const UINT *pX;
if (i == NextEndState) {
if (!bTwoRowsPadding && i == N - 1) {
diff --git a/drivers/d3d12/rendering_device_driver_d3d12.cpp b/drivers/d3d12/rendering_device_driver_d3d12.cpp
index 8271d4b7e38d..0ef88e7d5285 100644
--- a/drivers/d3d12/rendering_device_driver_d3d12.cpp
+++ b/drivers/d3d12/rendering_device_driver_d3d12.cpp
@@ -1348,7 +1348,14 @@ RDD::TextureID RenderingDeviceDriverD3D12::texture_create(const TextureFormat &p
}
tex_info->states_ptr = &tex_info->owner_info.states;
tex_info->format = p_format.format;
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif
tex_info->desc = *(CD3DX12_RESOURCE_DESC *)&resource_desc;
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC diagnostic pop
+#endif
tex_info->base_layer = 0;
tex_info->layers = resource_desc.ArraySize();
tex_info->base_mip = 0;
@@ -6578,8 +6585,6 @@ static Error create_command_signature(ID3D12Device *device, D3D12_INDIRECT_ARGUM
Error RenderingDeviceDriverD3D12::_initialize_frames(uint32_t p_frame_count) {
Error err;
- D3D12MA::ALLOCATION_DESC allocation_desc = {};
- allocation_desc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
//CD3DX12_RESOURCE_DESC resource_desc = CD3DX12_RESOURCE_DESC::Buffer(D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT);
uint32_t resource_descriptors_per_frame = GLOBAL_GET("rendering/rendering_device/d3d12/max_resource_descriptors_per_frame");
diff --git a/platform/windows/detect.py b/platform/windows/detect.py
index 4043f3a8c282..0ee52a09a7fe 100644
--- a/platform/windows/detect.py
+++ b/platform/windows/detect.py
@@ -662,7 +662,7 @@ def get_ar_version(env):
print_warning("Couldn't check version of `ar`.")
return ret
- match = re.search(r"GNU ar \(GNU Binutils\) (\d+)\.(\d+)(?:\.(\d+))?", output)
+ match = re.search(r"GNU ar(?: \(GNU Binutils\)| version) (\d+)\.(\d+)(?:\.(\d+))?", output)
if match:
ret["major"] = int(match[1])
ret["minor"] = int(match[2])
@@ -788,8 +788,9 @@ def configure_mingw(env: "SConsEnvironment"):
env["CXX"] = mingw_bin_prefix + "g++"
if try_cmd("as --version", env["mingw_prefix"], env["arch"]):
env["AS"] = mingw_bin_prefix + "as"
- if try_cmd("gcc-ar --version", env["mingw_prefix"], env["arch"]):
- env["AR"] = mingw_bin_prefix + "gcc-ar"
+ ar = "ar" if os.name == "nt" else "gcc-ar"
+ if try_cmd(f"{ar} --version", env["mingw_prefix"], env["arch"]):
+ env["AR"] = mingw_bin_prefix + ar
if try_cmd("gcc-ranlib --version", env["mingw_prefix"], env["arch"]):
env["RANLIB"] = mingw_bin_prefix + "gcc-ranlib"
| diff --git a/.github/workflows/windows_builds.yml b/.github/workflows/windows_builds.yml
index 95e3d4a553d1..384284b6047e 100644
--- a/.github/workflows/windows_builds.yml
+++ b/.github/workflows/windows_builds.yml
@@ -30,7 +30,7 @@ jobs:
# Skip debug symbols, they're way too big with MSVC.
sconsflags: debug_symbols=no vsproj=yes vsproj_gen_only=no windows_subsystem=console
bin: ./bin/godot.windows.editor.x86_64.exe
- name: Editor w/ clang-cl (target=editor, tests=yes, use_llvm=yes)
cache-name: windows-editor-clang
@@ -38,6 +38,7 @@ jobs:
sconsflags: debug_symbols=no windows_subsystem=console use_llvm=yes
bin: ./bin/godot.windows.editor.x86_64.llvm.exe
+ compiler: clang
- name: Template (target=template_release, tests=yes)
cache-name: windows-template
@@ -45,7 +46,16 @@ jobs:
sconsflags: debug_symbols=no
bin: ./bin/godot.windows.template_release.x86_64.console.exe
+ - name: Template w/ GCC (target=template_release, tests=yes, use_mingw=yes)
+ cache-name: windows-template-gcc
+ # MinGW takes MUCH longer to compile; save time by only targeting Template.
+ target: template_release
+ tests: true
+ bin: ./bin/godot.windows.template_release.x86_64.console.exe
+ compiler: gcc
steps:
- name: Checkout
@@ -69,16 +79,21 @@ jobs:
uses: dsaltares/[email protected]
repo: godotengine/godot-angle-static
+ version: tags/chromium/6601.2
+ file: godot-angle-static-x86_64-${{ matrix.compiler == 'gcc' && 'gcc' || 'msvc' }}-release.zip
target: angle/angle.zip
- name: Extract pre-built ANGLE static libraries
run: Expand-Archive -Force angle/angle.zip ${{ github.workspace }}/
- name: Setup MSVC problem matcher
uses: ammaraskar/msvc-problem-matcher@master
+ - name: Setup GCC problem matcher
+ if: matrix.compiler != 'msvc'
+ uses: ammaraskar/gcc-problem-matcher@master
- name: Compilation
uses: ./.github/actions/godot-build
@@ -94,12 +109,12 @@ jobs:
continue-on-error: true
- name: Prepare artifact
run: |
Remove-Item bin/* -Include *.exp,*.lib,*.pdb -Force
- name: Upload artifact
uses: ./.github/actions/upload-artifact
name: ${{ matrix.cache-name }}
diff --git a/drivers/d3d12/SCsub b/drivers/d3d12/SCsub
index b6ceed23ac83..beeb13398e37 100644
--- a/drivers/d3d12/SCsub
+++ b/drivers/d3d12/SCsub
@@ -4,6 +4,8 @@ from misc.utility.scons_hints import *
import os
from pathlib import Path
+import methods
Import("env")
env_d3d12_rdd = env.Clone()
@@ -139,6 +141,10 @@ else:
extra_defines += [
"HAVE_STRUCT_TIMESPEC",
]
+ if methods.using_gcc(env) and methods.get_compiler_version(env)["major"] < 13:
+ # `region` & `endregion` not recognized as valid pragmas.
+ env_d3d12_rdd.Append(CCFLAGS=["-Wno-unknown-pragmas"])
+ env.Append(CCFLAGS=["-Wno-unknown-pragmas"])
# This is needed since rendering_device_d3d12.cpp needs to include some Mesa internals.
env_d3d12_rdd.Prepend(CPPPATH=mesa_private_inc_paths)
diff --git a/drivers/d3d12/dxil_hash.cpp b/drivers/d3d12/dxil_hash.cpp
index f94a4a30df3c..e08492c9ea9f 100644
--- a/drivers/d3d12/dxil_hash.cpp
+++ b/drivers/d3d12/dxil_hash.cpp
@@ -96,7 +96,7 @@ void compute_dxil_hash(const BYTE *pData, UINT byteCount, BYTE *pOutHash) {
UINT NextEndState = bTwoRowsPadding ? N - 2 : N - 1;
const BYTE *pCurrData = pData;
for (UINT i = 0; i < N; i++, offset += 64, pCurrData += 64) {
- UINT x[16];
+ UINT x[16] = {};
const UINT *pX;
if (i == NextEndState) {
if (!bTwoRowsPadding && i == N - 1) {
diff --git a/drivers/d3d12/rendering_device_driver_d3d12.cpp b/drivers/d3d12/rendering_device_driver_d3d12.cpp
index 8271d4b7e38d..0ef88e7d5285 100644
--- a/drivers/d3d12/rendering_device_driver_d3d12.cpp
+++ b/drivers/d3d12/rendering_device_driver_d3d12.cpp
@@ -1348,7 +1348,14 @@ RDD::TextureID RenderingDeviceDriverD3D12::texture_create(const TextureFormat &p
}
tex_info->states_ptr = &tex_info->owner_info.states;
tex_info->format = p_format.format;
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wstrict-aliasing"
tex_info->desc = *(CD3DX12_RESOURCE_DESC *)&resource_desc;
+#pragma GCC diagnostic pop
tex_info->base_layer = 0;
tex_info->layers = resource_desc.ArraySize();
tex_info->base_mip = 0;
@@ -6578,8 +6585,6 @@ static Error create_command_signature(ID3D12Device *device, D3D12_INDIRECT_ARGUM
Error RenderingDeviceDriverD3D12::_initialize_frames(uint32_t p_frame_count) {
Error err;
- D3D12MA::ALLOCATION_DESC allocation_desc = {};
- allocation_desc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
//CD3DX12_RESOURCE_DESC resource_desc = CD3DX12_RESOURCE_DESC::Buffer(D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT);
uint32_t resource_descriptors_per_frame = GLOBAL_GET("rendering/rendering_device/d3d12/max_resource_descriptors_per_frame");
diff --git a/platform/windows/detect.py b/platform/windows/detect.py
index 4043f3a8c282..0ee52a09a7fe 100644
--- a/platform/windows/detect.py
+++ b/platform/windows/detect.py
@@ -662,7 +662,7 @@ def get_ar_version(env):
print_warning("Couldn't check version of `ar`.")
return ret
- match = re.search(r"GNU ar \(GNU Binutils\) (\d+)\.(\d+)(?:\.(\d+))?", output)
+ match = re.search(r"GNU ar(?: \(GNU Binutils\)| version) (\d+)\.(\d+)(?:\.(\d+))?", output)
if match:
ret["major"] = int(match[1])
ret["minor"] = int(match[2])
@@ -788,8 +788,9 @@ def configure_mingw(env: "SConsEnvironment"):
env["CXX"] = mingw_bin_prefix + "g++"
if try_cmd("as --version", env["mingw_prefix"], env["arch"]):
env["AS"] = mingw_bin_prefix + "as"
- if try_cmd("gcc-ar --version", env["mingw_prefix"], env["arch"]):
- env["AR"] = mingw_bin_prefix + "gcc-ar"
+ ar = "ar" if os.name == "nt" else "gcc-ar"
+ if try_cmd(f"{ar} --version", env["mingw_prefix"], env["arch"]):
+ env["AR"] = mingw_bin_prefix + ar
if try_cmd("gcc-ranlib --version", env["mingw_prefix"], env["arch"]):
env["RANLIB"] = mingw_bin_prefix + "gcc-ranlib" | [
"+ sconsflags: debug_symbols=no use_mingw=yes",
"- version: tags/chromium/6029",
"- file: Windows.6029-1.MSVC_17.x86_64.x86_32.zip"
] | [
33,
43,
44
] | {
"additions": 39,
"author": "Repiteo",
"deletions": 12,
"html_url": "https://github.com/godotengine/godot/pull/97446",
"issue_id": 97446,
"merged_at": "2024-10-10T23:24:19Z",
"omission_probability": 0.1,
"pr_number": 97446,
"repo": "godotengine/godot",
"title": "CI: Add MinGW/GCC build to Windows GHA",
"total_changes": 51
} |
713 | diff --git a/scene/gui/scroll_bar.cpp b/scene/gui/scroll_bar.cpp
index 0b9e21e7b317..d8a8ea01f423 100644
--- a/scene/gui/scroll_bar.cpp
+++ b/scene/gui/scroll_bar.cpp
@@ -50,13 +50,13 @@ void ScrollBar::gui_input(const Ref<InputEvent> &p_event) {
accept_event();
if (b->get_button_index() == MouseButton::WHEEL_DOWN && b->is_pressed()) {
- double change = get_page() != 0.0 ? get_page() / 4.0 : (get_max() - get_min()) / 16.0;
+ double change = ((get_page() != 0.0) ? get_page() / PAGE_DIVISOR : (get_max() - get_min()) / 16.0) * b->get_factor();
scroll(MAX(change, get_step()));
accept_event();
}
if (b->get_button_index() == MouseButton::WHEEL_UP && b->is_pressed()) {
- double change = get_page() != 0.0 ? get_page() / 4.0 : (get_max() - get_min()) / 16.0;
+ double change = ((get_page() != 0.0) ? get_page() / PAGE_DIVISOR : (get_max() - get_min()) / 16.0) * b->get_factor();
scroll(-MAX(change, get_step()));
accept_event();
}
diff --git a/scene/gui/scroll_bar.h b/scene/gui/scroll_bar.h
index b2d019c3506b..f2a49e4e7fac 100644
--- a/scene/gui/scroll_bar.h
+++ b/scene/gui/scroll_bar.h
@@ -110,6 +110,8 @@ class ScrollBar : public Range {
static void _bind_methods();
public:
+ static inline const int PAGE_DIVISOR = 8;
+
void scroll(double p_amount);
void scroll_to(double p_position);
diff --git a/scene/gui/scroll_container.cpp b/scene/gui/scroll_container.cpp
index 10803bf9b875..21486f12e302 100644
--- a/scene/gui/scroll_container.cpp
+++ b/scene/gui/scroll_container.cpp
@@ -129,19 +129,19 @@ void ScrollContainer::gui_input(const Ref<InputEvent> &p_gui_input) {
if (mb->get_button_index() == MouseButton::WHEEL_UP) {
// By default, the vertical orientation takes precedence. This is an exception.
if ((h_scroll_enabled && mb->is_shift_pressed()) || v_scroll_hidden) {
- h_scroll->scroll(-h_scroll->get_page() / 8 * mb->get_factor());
+ h_scroll->scroll(-h_scroll->get_page() / ScrollBar::PAGE_DIVISOR * mb->get_factor());
scroll_value_modified = true;
} else if (v_scroll_enabled) {
- v_scroll->scroll(-v_scroll->get_page() / 8 * mb->get_factor());
+ v_scroll->scroll(-v_scroll->get_page() / ScrollBar::PAGE_DIVISOR * mb->get_factor());
scroll_value_modified = true;
}
}
if (mb->get_button_index() == MouseButton::WHEEL_DOWN) {
if ((h_scroll_enabled && mb->is_shift_pressed()) || v_scroll_hidden) {
- h_scroll->scroll(h_scroll->get_page() / 8 * mb->get_factor());
+ h_scroll->scroll(h_scroll->get_page() / ScrollBar::PAGE_DIVISOR * mb->get_factor());
scroll_value_modified = true;
} else if (v_scroll_enabled) {
- v_scroll->scroll(v_scroll->get_page() / 8 * mb->get_factor());
+ v_scroll->scroll(v_scroll->get_page() / ScrollBar::PAGE_DIVISOR * mb->get_factor());
scroll_value_modified = true;
}
}
@@ -150,19 +150,19 @@ void ScrollContainer::gui_input(const Ref<InputEvent> &p_gui_input) {
if (mb->get_button_index() == MouseButton::WHEEL_LEFT) {
// By default, the horizontal orientation takes precedence. This is an exception.
if ((v_scroll_enabled && mb->is_shift_pressed()) || h_scroll_hidden) {
- v_scroll->scroll(-v_scroll->get_page() / 8 * mb->get_factor());
+ v_scroll->scroll(-v_scroll->get_page() / ScrollBar::PAGE_DIVISOR * mb->get_factor());
scroll_value_modified = true;
} else if (h_scroll_enabled) {
- h_scroll->scroll(-h_scroll->get_page() / 8 * mb->get_factor());
+ h_scroll->scroll(-h_scroll->get_page() / ScrollBar::PAGE_DIVISOR * mb->get_factor());
scroll_value_modified = true;
}
}
if (mb->get_button_index() == MouseButton::WHEEL_RIGHT) {
if ((v_scroll_enabled && mb->is_shift_pressed()) || h_scroll_hidden) {
- v_scroll->scroll(v_scroll->get_page() / 8 * mb->get_factor());
+ v_scroll->scroll(v_scroll->get_page() / ScrollBar::PAGE_DIVISOR * mb->get_factor());
scroll_value_modified = true;
} else if (h_scroll_enabled) {
- h_scroll->scroll(h_scroll->get_page() / 8 * mb->get_factor());
+ h_scroll->scroll(h_scroll->get_page() / ScrollBar::PAGE_DIVISOR * mb->get_factor());
scroll_value_modified = true;
}
}
@@ -250,10 +250,10 @@ void ScrollContainer::gui_input(const Ref<InputEvent> &p_gui_input) {
Ref<InputEventPanGesture> pan_gesture = p_gui_input;
if (pan_gesture.is_valid()) {
if (h_scroll_enabled) {
- h_scroll->scroll(h_scroll->get_page() * pan_gesture->get_delta().x / 8);
+ h_scroll->scroll(h_scroll->get_page() * pan_gesture->get_delta().x / ScrollBar::PAGE_DIVISOR);
}
if (v_scroll_enabled) {
- v_scroll->scroll(v_scroll->get_page() * pan_gesture->get_delta().y / 8);
+ v_scroll->scroll(v_scroll->get_page() * pan_gesture->get_delta().y / ScrollBar::PAGE_DIVISOR);
}
if (v_scroll->get_value() != prev_v_scroll || h_scroll->get_value() != prev_h_scroll) {
@@ -411,19 +411,19 @@ void ScrollContainer::_accessibility_action_scroll_set(const Variant &p_data) {
}
void ScrollContainer::_accessibility_action_scroll_up(const Variant &p_data) {
- v_scroll->set_value(v_scroll->get_value() - v_scroll->get_page() / 8);
+ v_scroll->set_value(v_scroll->get_value() - v_scroll->get_page() / ScrollBar::PAGE_DIVISOR);
}
void ScrollContainer::_accessibility_action_scroll_down(const Variant &p_data) {
- v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() / 8);
+ v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() / ScrollBar::PAGE_DIVISOR);
}
void ScrollContainer::_accessibility_action_scroll_left(const Variant &p_data) {
- h_scroll->set_value(h_scroll->get_value() - h_scroll->get_page() / 8);
+ h_scroll->set_value(h_scroll->get_value() - h_scroll->get_page() / ScrollBar::PAGE_DIVISOR);
}
void ScrollContainer::_accessibility_action_scroll_right(const Variant &p_data) {
- h_scroll->set_value(h_scroll->get_value() + h_scroll->get_page() / 8);
+ h_scroll->set_value(h_scroll->get_value() + h_scroll->get_page() / ScrollBar::PAGE_DIVISOR);
}
void ScrollContainer::_notification(int p_what) {
| diff --git a/scene/gui/scroll_bar.cpp b/scene/gui/scroll_bar.cpp
index 0b9e21e7b317..d8a8ea01f423 100644
--- a/scene/gui/scroll_bar.cpp
+++ b/scene/gui/scroll_bar.cpp
@@ -50,13 +50,13 @@ void ScrollBar::gui_input(const Ref<InputEvent> &p_event) {
accept_event();
if (b->get_button_index() == MouseButton::WHEEL_DOWN && b->is_pressed()) {
scroll(MAX(change, get_step()));
if (b->get_button_index() == MouseButton::WHEEL_UP && b->is_pressed()) {
scroll(-MAX(change, get_step()));
diff --git a/scene/gui/scroll_bar.h b/scene/gui/scroll_bar.h
index b2d019c3506b..f2a49e4e7fac 100644
--- a/scene/gui/scroll_bar.h
+++ b/scene/gui/scroll_bar.h
@@ -110,6 +110,8 @@ class ScrollBar : public Range {
static void _bind_methods();
public:
+ static inline const int PAGE_DIVISOR = 8;
void scroll(double p_amount);
void scroll_to(double p_position);
diff --git a/scene/gui/scroll_container.cpp b/scene/gui/scroll_container.cpp
index 10803bf9b875..21486f12e302 100644
--- a/scene/gui/scroll_container.cpp
+++ b/scene/gui/scroll_container.cpp
@@ -129,19 +129,19 @@ void ScrollContainer::gui_input(const Ref<InputEvent> &p_gui_input) {
if (mb->get_button_index() == MouseButton::WHEEL_UP) {
// By default, the vertical orientation takes precedence. This is an exception.
if (mb->get_button_index() == MouseButton::WHEEL_DOWN) {
@@ -150,19 +150,19 @@ void ScrollContainer::gui_input(const Ref<InputEvent> &p_gui_input) {
if (mb->get_button_index() == MouseButton::WHEEL_LEFT) {
// By default, the horizontal orientation takes precedence. This is an exception.
if (mb->get_button_index() == MouseButton::WHEEL_RIGHT) {
@@ -250,10 +250,10 @@ void ScrollContainer::gui_input(const Ref<InputEvent> &p_gui_input) {
Ref<InputEventPanGesture> pan_gesture = p_gui_input;
if (pan_gesture.is_valid()) {
if (h_scroll_enabled) {
- h_scroll->scroll(h_scroll->get_page() * pan_gesture->get_delta().x / 8);
+ h_scroll->scroll(h_scroll->get_page() * pan_gesture->get_delta().x / ScrollBar::PAGE_DIVISOR);
if (v_scroll_enabled) {
- v_scroll->scroll(v_scroll->get_page() * pan_gesture->get_delta().y / 8);
+ v_scroll->scroll(v_scroll->get_page() * pan_gesture->get_delta().y / ScrollBar::PAGE_DIVISOR);
if (v_scroll->get_value() != prev_v_scroll || h_scroll->get_value() != prev_h_scroll) {
@@ -411,19 +411,19 @@ void ScrollContainer::_accessibility_action_scroll_set(const Variant &p_data) {
void ScrollContainer::_accessibility_action_scroll_up(const Variant &p_data) {
- v_scroll->set_value(v_scroll->get_value() - v_scroll->get_page() / 8);
+ v_scroll->set_value(v_scroll->get_value() - v_scroll->get_page() / ScrollBar::PAGE_DIVISOR);
void ScrollContainer::_accessibility_action_scroll_down(const Variant &p_data) {
- v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() / 8);
+ v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() / ScrollBar::PAGE_DIVISOR);
void ScrollContainer::_accessibility_action_scroll_left(const Variant &p_data) {
- h_scroll->set_value(h_scroll->get_value() - h_scroll->get_page() / 8);
+ h_scroll->set_value(h_scroll->get_value() - h_scroll->get_page() / ScrollBar::PAGE_DIVISOR);
void ScrollContainer::_accessibility_action_scroll_right(const Variant &p_data) {
- h_scroll->set_value(h_scroll->get_value() + h_scroll->get_page() / 8);
+ h_scroll->set_value(h_scroll->get_value() + h_scroll->get_page() / ScrollBar::PAGE_DIVISOR);
void ScrollContainer::_notification(int p_what) { | [
"+"
] | [
29
] | {
"additions": 18,
"author": "tehKaiN",
"deletions": 16,
"html_url": "https://github.com/godotengine/godot/pull/105516",
"issue_id": 105516,
"merged_at": "2025-04-24T14:14:24Z",
"omission_probability": 0.1,
"pr_number": 105516,
"repo": "godotengine/godot",
"title": "Unify ScrollBar/ScrollContainer scroll delta",
"total_changes": 34
} |
714 | diff --git a/platform/android/SCsub b/platform/android/SCsub
index ca0747b5368c..14a648458393 100644
--- a/platform/android/SCsub
+++ b/platform/android/SCsub
@@ -1,6 +1,7 @@
#!/usr/bin/env python
from misc.utility.scons_hints import *
+import platform
import subprocess
import sys
@@ -51,18 +52,34 @@ lib = env_android.add_shared_library("#bin/libgodot", android_objects, redirect_
env.Depends(lib, thirdparty_obj)
lib_arch_dir = ""
+triple_target_dir = ""
if env["arch"] == "arm32":
lib_arch_dir = "armeabi-v7a"
+ triple_target_dir = "arm-linux-androideabi"
elif env["arch"] == "arm64":
lib_arch_dir = "arm64-v8a"
+ triple_target_dir = "aarch64-linux-android"
elif env["arch"] == "x86_32":
lib_arch_dir = "x86"
+ triple_target_dir = "i686-linux-android"
elif env["arch"] == "x86_64":
lib_arch_dir = "x86_64"
+ triple_target_dir = "x86_64-linux-android"
else:
print_warning("Architecture not suitable for embedding into APK; keeping .so at \\bin")
-if lib_arch_dir != "":
+host_subpath = ""
+if sys.platform.startswith("linux"):
+ host_subpath = "linux-x86_64"
+elif sys.platform.startswith("darwin"):
+ host_subpath = "darwin-x86_64"
+elif sys.platform.startswith("win"):
+ if platform.machine().endswith("64"):
+ host_subpath = "windows-x86_64"
+ else:
+ host_subpath = "windows"
+
+if lib_arch_dir != "" and host_subpath != "":
if env.dev_build:
lib_type_dir = "dev"
elif env.debug_features:
@@ -81,9 +98,7 @@ if lib_arch_dir != "":
out_dir = "#platform/android/java/lib/libs/" + lib_tools_dir + lib_type_dir + "/" + lib_arch_dir
env_android.CommandNoCache(out_dir + "/libgodot_android.so", lib, Move("$TARGET", "$SOURCE"))
- stl_lib_path = (
- str(env["ANDROID_NDK_ROOT"]) + "/sources/cxx-stl/llvm-libc++/libs/" + lib_arch_dir + "/libc++_shared.so"
- )
+ stl_lib_path = f"{env['ANDROID_NDK_ROOT']}/toolchains/llvm/prebuilt/{host_subpath}/sysroot/usr/lib/{triple_target_dir}/libc++_shared.so"
env_android.CommandNoCache(out_dir + "/libc++_shared.so", stl_lib_path, Copy("$TARGET", "$SOURCE"))
def generate_android_binaries(target, source, env):
@@ -98,10 +113,11 @@ if lib_arch_dir != "":
else:
gradle_process = ["./gradlew"]
- gradle_process += [
- "generateGodotEditor" if env["target"] == "editor" else "generateGodotTemplates",
- "--quiet",
- ]
+ if env["target"] == "editor":
+ gradle_process += ["generateGodotEditor", "generateGodotHorizonOSEditor", "generateGodotPicoOSEditor"]
+ else:
+ gradle_process += ["generateGodotTemplates"]
+ gradle_process += ["--quiet"]
if env["gradle_do_not_strip"]:
gradle_process += ["-PdoNotStrip=true"]
diff --git a/platform/android/detect.py b/platform/android/detect.py
index 4e600f6f7fe7..fe5f977a5855 100644
--- a/platform/android/detect.py
+++ b/platform/android/detect.py
@@ -69,7 +69,7 @@ def get_android_ndk_root(env: "SConsEnvironment"):
# This is kept in sync with the value in 'platform/android/java/app/config.gradle'.
def get_ndk_version():
- return "23.2.8568313"
+ return "27.2.12479018"
# This is kept in sync with the value in 'platform/android/java/app/config.gradle'.
diff --git a/platform/android/java/app/config.gradle b/platform/android/java/app/config.gradle
index af32a0de22e6..288c13237118 100644
--- a/platform/android/java/app/config.gradle
+++ b/platform/android/java/app/config.gradle
@@ -11,7 +11,7 @@ ext.versions = [
nexusPublishVersion: '1.3.0',
javaVersion : JavaVersion.VERSION_17,
// Also update 'platform/android/detect.py#get_ndk_version()' when this is updated.
- ndkVersion : '23.2.8568313',
+ ndkVersion : '27.2.12479018',
splashscreenVersion: '1.0.1',
openxrVendorsVersion: '3.1.2-stable'
diff --git a/platform/android/java/scripts/publish-module.gradle b/platform/android/java/scripts/publish-module.gradle
index d0fec9af19d0..8140c14685f8 100644
--- a/platform/android/java/scripts/publish-module.gradle
+++ b/platform/android/java/scripts/publish-module.gradle
@@ -43,7 +43,11 @@ afterEvaluate {
name = 'Rémi Verschelde'
email = '[email protected]'
}
- // Add all other devs here...
+ developer {
+ id = 'godotengine'
+ name = 'Godot Engine contributors'
+ email = '[email protected]'
+ }
}
// Version control info - if you're using GitHub, follow the
@@ -91,7 +95,11 @@ afterEvaluate {
name = 'Rémi Verschelde'
email = '[email protected]'
}
- // Add all other devs here...
+ developer {
+ id = 'godotengine'
+ name = 'Godot Engine contributors'
+ email = '[email protected]'
+ }
}
// Version control info - if you're using GitHub, follow the
| diff --git a/platform/android/SCsub b/platform/android/SCsub
index ca0747b5368c..14a648458393 100644
--- a/platform/android/SCsub
+++ b/platform/android/SCsub
@@ -1,6 +1,7 @@
#!/usr/bin/env python
from misc.utility.scons_hints import *
+import platform
import subprocess
import sys
@@ -51,18 +52,34 @@ lib = env_android.add_shared_library("#bin/libgodot", android_objects, redirect_
env.Depends(lib, thirdparty_obj)
lib_arch_dir = ""
+triple_target_dir = ""
if env["arch"] == "arm32":
lib_arch_dir = "armeabi-v7a"
+ triple_target_dir = "arm-linux-androideabi"
elif env["arch"] == "arm64":
lib_arch_dir = "arm64-v8a"
+ triple_target_dir = "aarch64-linux-android"
elif env["arch"] == "x86_32":
lib_arch_dir = "x86"
+ triple_target_dir = "i686-linux-android"
elif env["arch"] == "x86_64":
lib_arch_dir = "x86_64"
else:
print_warning("Architecture not suitable for embedding into APK; keeping .so at \\bin")
-if lib_arch_dir != "":
+host_subpath = ""
+if sys.platform.startswith("linux"):
+ host_subpath = "linux-x86_64"
+elif sys.platform.startswith("darwin"):
+ host_subpath = "darwin-x86_64"
+elif sys.platform.startswith("win"):
+ if platform.machine().endswith("64"):
+ host_subpath = "windows-x86_64"
+ else:
+
+if lib_arch_dir != "" and host_subpath != "":
if env.dev_build:
lib_type_dir = "dev"
elif env.debug_features:
@@ -81,9 +98,7 @@ if lib_arch_dir != "":
out_dir = "#platform/android/java/lib/libs/" + lib_tools_dir + lib_type_dir + "/" + lib_arch_dir
env_android.CommandNoCache(out_dir + "/libgodot_android.so", lib, Move("$TARGET", "$SOURCE"))
- stl_lib_path = (
- )
+ stl_lib_path = f"{env['ANDROID_NDK_ROOT']}/toolchains/llvm/prebuilt/{host_subpath}/sysroot/usr/lib/{triple_target_dir}/libc++_shared.so"
env_android.CommandNoCache(out_dir + "/libc++_shared.so", stl_lib_path, Copy("$TARGET", "$SOURCE"))
def generate_android_binaries(target, source, env):
@@ -98,10 +113,11 @@ if lib_arch_dir != "":
else:
gradle_process = ["./gradlew"]
- gradle_process += [
- "generateGodotEditor" if env["target"] == "editor" else "generateGodotTemplates",
- ]
+ gradle_process += ["generateGodotEditor", "generateGodotHorizonOSEditor", "generateGodotPicoOSEditor"]
+ else:
+ gradle_process += ["generateGodotTemplates"]
+ gradle_process += ["--quiet"]
if env["gradle_do_not_strip"]:
gradle_process += ["-PdoNotStrip=true"]
diff --git a/platform/android/detect.py b/platform/android/detect.py
index 4e600f6f7fe7..fe5f977a5855 100644
--- a/platform/android/detect.py
+++ b/platform/android/detect.py
@@ -69,7 +69,7 @@ def get_android_ndk_root(env: "SConsEnvironment"):
def get_ndk_version():
- return "23.2.8568313"
+ return "27.2.12479018"
diff --git a/platform/android/java/app/config.gradle b/platform/android/java/app/config.gradle
index af32a0de22e6..288c13237118 100644
--- a/platform/android/java/app/config.gradle
+++ b/platform/android/java/app/config.gradle
@@ -11,7 +11,7 @@ ext.versions = [
nexusPublishVersion: '1.3.0',
javaVersion : JavaVersion.VERSION_17,
// Also update 'platform/android/detect.py#get_ndk_version()' when this is updated.
- ndkVersion : '23.2.8568313',
+ ndkVersion : '27.2.12479018',
splashscreenVersion: '1.0.1',
openxrVendorsVersion: '3.1.2-stable'
diff --git a/platform/android/java/scripts/publish-module.gradle b/platform/android/java/scripts/publish-module.gradle
index d0fec9af19d0..8140c14685f8 100644
--- a/platform/android/java/scripts/publish-module.gradle
+++ b/platform/android/java/scripts/publish-module.gradle
@@ -43,7 +43,11 @@ afterEvaluate {
@@ -91,7 +95,11 @@ afterEvaluate { | [
"+ triple_target_dir = \"x86_64-linux-android\"",
"+ host_subpath = \"windows\"",
"- str(env[\"ANDROID_NDK_ROOT\"]) + \"/sources/cxx-stl/llvm-libc++/libs/\" + lib_arch_dir + \"/libc++_shared.so\"",
"- \"--quiet\",",
"+ if env[\"target\"] == \"editor\":"
] | [
28,
42,
53,
65,
67
] | {
"additions": 36,
"author": "m4gr3d",
"deletions": 12,
"html_url": "https://github.com/godotengine/godot/pull/105611",
"issue_id": 105611,
"merged_at": "2025-04-24T14:14:24Z",
"omission_probability": 0.1,
"pr_number": 105611,
"repo": "godotengine/godot",
"title": "Update the Android NDK to the latest LTS version (r27c)",
"total_changes": 48
} |
715 | diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp
index bc55603a1941..9c0b2f5477db 100644
--- a/modules/gdscript/gdscript_analyzer.cpp
+++ b/modules/gdscript/gdscript_analyzer.cpp
@@ -5197,24 +5197,29 @@ void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op)
}
Variant GDScriptAnalyzer::make_expression_reduced_value(GDScriptParser::ExpressionNode *p_expression, bool &is_reduced) {
- Variant value;
-
if (p_expression == nullptr) {
- return value;
+ return Variant();
}
if (p_expression->is_constant) {
is_reduced = true;
- value = p_expression->reduced_value;
- } else if (p_expression->type == GDScriptParser::Node::ARRAY) {
- value = make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);
- } else if (p_expression->type == GDScriptParser::Node::DICTIONARY) {
- value = make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);
- } else if (p_expression->type == GDScriptParser::Node::SUBSCRIPT) {
- value = make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);
+ return p_expression->reduced_value;
}
- return value;
+ switch (p_expression->type) {
+ case GDScriptParser::Node::ARRAY:
+ return make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);
+ case GDScriptParser::Node::DICTIONARY:
+ return make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);
+ case GDScriptParser::Node::SUBSCRIPT:
+ return make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);
+ case GDScriptParser::Node::CALL:
+ return make_call_reduced_value(static_cast<GDScriptParser::CallNode *>(p_expression), is_reduced);
+ default:
+ break;
+ }
+
+ return Variant();
}
Variant GDScriptAnalyzer::make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced) {
@@ -5306,6 +5311,53 @@ Variant GDScriptAnalyzer::make_subscript_reduced_value(GDScriptParser::Subscript
}
}
+Variant GDScriptAnalyzer::make_call_reduced_value(GDScriptParser::CallNode *p_call, bool &is_reduced) {
+ if (p_call->get_callee_type() == GDScriptParser::Node::IDENTIFIER) {
+ Variant::Type type = Variant::NIL;
+ if (p_call->function_name == SNAME("Array")) {
+ type = Variant::ARRAY;
+ } else if (p_call->function_name == SNAME("Dictionary")) {
+ type = Variant::DICTIONARY;
+ } else {
+ return Variant();
+ }
+
+ Vector<Variant> args;
+ args.resize(p_call->arguments.size());
+ const Variant **argptrs = (const Variant **)alloca(sizeof(const Variant **) * args.size());
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ bool is_arg_value_reduced = false;
+ Variant arg_value = make_expression_reduced_value(p_call->arguments[i], is_arg_value_reduced);
+ if (!is_arg_value_reduced) {
+ return Variant();
+ }
+ args.write[i] = arg_value;
+ argptrs[i] = &args[i];
+ }
+
+ Variant result;
+ Callable::CallError ce;
+ Variant::construct(type, result, argptrs, args.size(), ce);
+ if (ce.error) {
+ push_error(vformat(R"(Failed to construct "%s".)", Variant::get_type_name(type)), p_call);
+ return Variant();
+ }
+
+ if (type == Variant::ARRAY) {
+ Array array = result;
+ array.make_read_only();
+ } else if (type == Variant::DICTIONARY) {
+ Dictionary dictionary = result;
+ dictionary.make_read_only();
+ }
+
+ is_reduced = true;
+ return result;
+ }
+
+ return Variant();
+}
+
Array GDScriptAnalyzer::make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node) {
Array array;
diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h
index 2a90e65c0bb6..576276471d3a 100644
--- a/modules/gdscript/gdscript_analyzer.h
+++ b/modules/gdscript/gdscript_analyzer.h
@@ -120,6 +120,7 @@ class GDScriptAnalyzer {
Variant make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced);
Variant make_dictionary_reduced_value(GDScriptParser::DictionaryNode *p_dictionary, bool &is_reduced);
Variant make_subscript_reduced_value(GDScriptParser::SubscriptNode *p_subscript, bool &is_reduced);
+ Variant make_call_reduced_value(GDScriptParser::CallNode *p_call, bool &is_reduced);
// Helpers.
Array make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node = nullptr);
diff --git a/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.gd b/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.gd
new file mode 100644
index 000000000000..752ffc1311ae
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.gd
@@ -0,0 +1,64 @@
+const A1 = Array()
+const A2 = Array(Array())
+const A3 = Array([])
+const A4 = [Array()]
+const A5 = [[]]
+const A6 = Array([1], TYPE_INT, &"", null)
+
+const D1 = Dictionary()
+const D2 = Dictionary(Dictionary())
+const D3 = Dictionary({})
+const D4 = { Dictionary(): Dictionary() }
+const D5 = { {}: {} }
+const D6 = Dictionary({ 1: 1 }, TYPE_INT, &"", null, TYPE_INT, &"", null)
+
+var a1 = Array()
+var a2 = Array(Array())
+var a3 = Array([])
+var a4 = [Array()]
+var a5 = [[]]
+var a6 = Array([1], TYPE_INT, &"", null)
+
+var d1 = Dictionary()
+var d2 = Dictionary(Dictionary())
+var d3 = Dictionary({})
+var d4 = { Dictionary(): Dictionary() }
+var d5 = { {}: {} }
+var d6 = Dictionary({ 1: 1 }, TYPE_INT, &"", null, TYPE_INT, &"", null)
+
+func test_value(value: Variant) -> void:
+ @warning_ignore("unsafe_method_access")
+ prints(value.is_read_only(), var_to_str(value).replace("\n", " "))
+
+func test():
+ print('---')
+ test_value(A1)
+ test_value(A2)
+ test_value(A3)
+ test_value(A4)
+ test_value(A5)
+ test_value(A6)
+
+ print('---')
+ test_value(D1)
+ test_value(D2)
+ test_value(D3)
+ test_value(D4)
+ test_value(D5)
+ test_value(D6)
+
+ print('---')
+ test_value(a1)
+ test_value(a2)
+ test_value(a3)
+ test_value(a4)
+ test_value(a5)
+ test_value(a6)
+
+ print('---')
+ test_value(d1)
+ test_value(d2)
+ test_value(d3)
+ test_value(d4)
+ test_value(d5)
+ test_value(d6)
diff --git a/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.out b/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.out
new file mode 100644
index 000000000000..428251a31157
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.out
@@ -0,0 +1,29 @@
+GDTEST_OK
+---
+true []
+true []
+true []
+true [[]]
+true [[]]
+true Array[int]([1])
+---
+true {}
+true {}
+true {}
+true { {}: {} }
+true { {}: {} }
+true Dictionary[int, int]({ 1: 1 })
+---
+false []
+false []
+false []
+false [[]]
+false [[]]
+false Array[int]([1])
+---
+false {}
+false {}
+false {}
+false { {}: {} }
+false { {}: {} }
+false Dictionary[int, int]({ 1: 1 })
| diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp
index bc55603a1941..9c0b2f5477db 100644
--- a/modules/gdscript/gdscript_analyzer.cpp
+++ b/modules/gdscript/gdscript_analyzer.cpp
@@ -5197,24 +5197,29 @@ void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op)
Variant GDScriptAnalyzer::make_expression_reduced_value(GDScriptParser::ExpressionNode *p_expression, bool &is_reduced) {
- Variant value;
-
if (p_expression == nullptr) {
+ return Variant();
if (p_expression->is_constant) {
is_reduced = true;
- value = p_expression->reduced_value;
- } else if (p_expression->type == GDScriptParser::Node::ARRAY) {
- value = make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);
- } else if (p_expression->type == GDScriptParser::Node::DICTIONARY) {
- value = make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);
- } else if (p_expression->type == GDScriptParser::Node::SUBSCRIPT) {
- value = make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);
+ return p_expression->reduced_value;
- return value;
+ switch (p_expression->type) {
+ case GDScriptParser::Node::ARRAY:
+ return make_array_reduced_value(static_cast<GDScriptParser::ArrayNode *>(p_expression), is_reduced);
+ case GDScriptParser::Node::DICTIONARY:
+ return make_dictionary_reduced_value(static_cast<GDScriptParser::DictionaryNode *>(p_expression), is_reduced);
+ case GDScriptParser::Node::SUBSCRIPT:
+ return make_subscript_reduced_value(static_cast<GDScriptParser::SubscriptNode *>(p_expression), is_reduced);
+ return make_call_reduced_value(static_cast<GDScriptParser::CallNode *>(p_expression), is_reduced);
+ default:
+ break;
Variant GDScriptAnalyzer::make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced) {
@@ -5306,6 +5311,53 @@ Variant GDScriptAnalyzer::make_subscript_reduced_value(GDScriptParser::Subscript
+Variant GDScriptAnalyzer::make_call_reduced_value(GDScriptParser::CallNode *p_call, bool &is_reduced) {
+ if (p_call->get_callee_type() == GDScriptParser::Node::IDENTIFIER) {
+ Variant::Type type = Variant::NIL;
+ if (p_call->function_name == SNAME("Array")) {
+ } else if (p_call->function_name == SNAME("Dictionary")) {
+ type = Variant::DICTIONARY;
+ } else {
+ Vector<Variant> args;
+ args.resize(p_call->arguments.size());
+ const Variant **argptrs = (const Variant **)alloca(sizeof(const Variant **) * args.size());
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ bool is_arg_value_reduced = false;
+ Variant arg_value = make_expression_reduced_value(p_call->arguments[i], is_arg_value_reduced);
+ if (!is_arg_value_reduced) {
+ return Variant();
+ }
+ args.write[i] = arg_value;
+ argptrs[i] = &args[i];
+ Variant result;
+ Callable::CallError ce;
+ Variant::construct(type, result, argptrs, args.size(), ce);
+ if (ce.error) {
+ if (type == Variant::ARRAY) {
+ array.make_read_only();
+ } else if (type == Variant::DICTIONARY) {
+ Dictionary dictionary = result;
+ dictionary.make_read_only();
+ is_reduced = true;
+ return result;
+}
Array GDScriptAnalyzer::make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node) {
Array array;
diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h
index 2a90e65c0bb6..576276471d3a 100644
--- a/modules/gdscript/gdscript_analyzer.h
+++ b/modules/gdscript/gdscript_analyzer.h
@@ -120,6 +120,7 @@ class GDScriptAnalyzer {
Variant make_array_reduced_value(GDScriptParser::ArrayNode *p_array, bool &is_reduced);
Variant make_dictionary_reduced_value(GDScriptParser::DictionaryNode *p_dictionary, bool &is_reduced);
Variant make_subscript_reduced_value(GDScriptParser::SubscriptNode *p_subscript, bool &is_reduced);
+ Variant make_call_reduced_value(GDScriptParser::CallNode *p_call, bool &is_reduced);
// Helpers.
Array make_array_from_element_datatype(const GDScriptParser::DataType &p_element_datatype, const GDScriptParser::Node *p_source_node = nullptr);
diff --git a/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.gd b/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.gd
index 000000000000..752ffc1311ae
+++ b/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.gd
@@ -0,0 +1,64 @@
+const A1 = Array()
+const A2 = Array(Array())
+const A3 = Array([])
+const A4 = [Array()]
+const A5 = [[]]
+const A6 = Array([1], TYPE_INT, &"", null)
+const D1 = Dictionary()
+const D2 = Dictionary(Dictionary())
+const D3 = Dictionary({})
+const D4 = { Dictionary(): Dictionary() }
+const D5 = { {}: {} }
+const D6 = Dictionary({ 1: 1 }, TYPE_INT, &"", null, TYPE_INT, &"", null)
+var a1 = Array()
+var a2 = Array(Array())
+var a3 = Array([])
+var a4 = [Array()]
+var a5 = [[]]
+var a6 = Array([1], TYPE_INT, &"", null)
+var d1 = Dictionary()
+var d2 = Dictionary(Dictionary())
+var d3 = Dictionary({})
+var d4 = { Dictionary(): Dictionary() }
+var d5 = { {}: {} }
+var d6 = Dictionary({ 1: 1 }, TYPE_INT, &"", null, TYPE_INT, &"", null)
+func test_value(value: Variant) -> void:
+ @warning_ignore("unsafe_method_access")
+ prints(value.is_read_only(), var_to_str(value).replace("\n", " "))
+ test_value(A1)
+ test_value(A2)
+ test_value(A4)
+ test_value(A5)
+ test_value(A6)
+ test_value(D1)
+ test_value(D2)
+ test_value(D3)
+ test_value(D4)
+ test_value(D5)
+ test_value(D6)
+ test_value(a1)
+ test_value(a2)
+ test_value(a3)
+ test_value(a4)
+ test_value(a6)
+ test_value(d1)
+ test_value(d2)
+ test_value(d3)
+ test_value(d4)
+ test_value(d5)
+ test_value(d6)
diff --git a/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.out b/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.out
index 000000000000..428251a31157
+++ b/modules/gdscript/tests/scripts/analyzer/features/const_array_and_dictionary_constructors.out
@@ -0,0 +1,29 @@
+GDTEST_OK
+true Array[int]([1])
+true Dictionary[int, int]({ 1: 1 })
+false Array[int]([1])
+false Dictionary[int, int]({ 1: 1 }) | [
"-\t\treturn value;",
"+\t\tcase GDScriptParser::Node::CALL:",
"+\t\t\ttype = Variant::ARRAY;",
"+\t\t\tpush_error(vformat(R\"(Failed to construct \"%s\".)\", Variant::get_type_name(type)), p_call);",
"+\t\t\tArray array = result;",
"+func test():",
"+\ttest_value(A3)",
"+\ttest_value(a5)"
] | [
11,
35,
53,
77,
82,
149,
153,
171
] | {
"additions": 157,
"author": "dalexeev",
"deletions": 11,
"html_url": "https://github.com/godotengine/godot/pull/78837",
"issue_id": 78837,
"merged_at": "2025-04-24T14:14:25Z",
"omission_probability": 0.1,
"pr_number": 78837,
"repo": "godotengine/godot",
"title": "GDScript: Add constant `Array` and `Dictionary` constructors",
"total_changes": 168
} |
716 | diff --git a/editor/debugger/debug_adapter/debug_adapter_protocol.cpp b/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
index 17f0b9bef56c..61a785066c56 100644
--- a/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
+++ b/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
@@ -1130,12 +1130,14 @@ void DebugAdapterProtocol::on_debug_data(const String &p_msg, const Array &p_dat
return;
}
- if (p_msg == "scene:inspect_object") {
- // An object was requested from the debuggee; parse it.
- SceneDebuggerObject remote_obj;
- remote_obj.deserialize(p_data);
+ if (p_msg == "scene:inspect_objects") {
+ if (!p_data.is_empty()) {
+ // An object was requested from the debuggee; parse it.
+ SceneDebuggerObject remote_obj;
+ remote_obj.deserialize(p_data[0]);
- parse_object(remote_obj);
+ parse_object(remote_obj);
+ }
} else if (p_msg == "evaluation_return") {
// An evaluation was requested from the debuggee; parse it.
DebuggerMarshalls::ScriptStackVariable remote_evaluation;
| diff --git a/editor/debugger/debug_adapter/debug_adapter_protocol.cpp b/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
index 17f0b9bef56c..61a785066c56 100644
--- a/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
+++ b/editor/debugger/debug_adapter/debug_adapter_protocol.cpp
@@ -1130,12 +1130,14 @@ void DebugAdapterProtocol::on_debug_data(const String &p_msg, const Array &p_dat
return;
}
- if (p_msg == "scene:inspect_object") {
- // An object was requested from the debuggee; parse it.
- SceneDebuggerObject remote_obj;
- remote_obj.deserialize(p_data);
+ if (p_msg == "scene:inspect_objects") {
+ if (!p_data.is_empty()) {
+ // An object was requested from the debuggee; parse it.
+ SceneDebuggerObject remote_obj;
+ remote_obj.deserialize(p_data[0]);
- parse_object(remote_obj);
+ parse_object(remote_obj);
+ }
} else if (p_msg == "evaluation_return") {
// An evaluation was requested from the debuggee; parse it.
DebuggerMarshalls::ScriptStackVariable remote_evaluation; | [] | [] | {
"additions": 7,
"author": "YeldhamDev",
"deletions": 5,
"html_url": "https://github.com/godotengine/godot/pull/104842",
"issue_id": 104842,
"merged_at": "2025-04-24T14:14:24Z",
"omission_probability": 0.1,
"pr_number": 104842,
"repo": "godotengine/godot",
"title": "Fix remote object inspector through DAP",
"total_changes": 12
} |
717 | diff --git a/thirdparty/jolt_physics/Jolt/Core/Memory.h b/thirdparty/jolt_physics/Jolt/Core/Memory.h
index b5f318db1cfb..4f3dbc7d1326 100644
--- a/thirdparty/jolt_physics/Jolt/Core/Memory.h
+++ b/thirdparty/jolt_physics/Jolt/Core/Memory.h
@@ -27,12 +27,24 @@ JPH_EXPORT extern AlignedFreeFunction AlignedFree;
/// Register platform default allocation / free functions
JPH_EXPORT void RegisterDefaultAllocator();
+// 32-bit MinGW g++ doesn't call the correct overload for the new operator when a type is 16 bytes aligned.
+// It uses the non-aligned version, which on 32 bit platforms usually returns an 8 byte aligned block.
+// We therefore default to 16 byte aligned allocations when the regular new operator is used.
+// See: https://github.com/godotengine/godot/issues/105455#issuecomment-2824311547
+#if defined(JPH_COMPILER_MINGW) && JPH_CPU_ADDRESS_BITS == 32
+ #define JPH_INTERNAL_DEFAULT_ALLOCATE(size) JPH::AlignedAllocate(size, 16)
+ #define JPH_INTERNAL_DEFAULT_FREE(pointer) JPH::AlignedFree(pointer)
+#else
+ #define JPH_INTERNAL_DEFAULT_ALLOCATE(size) JPH::Allocate(size)
+ #define JPH_INTERNAL_DEFAULT_FREE(pointer) JPH::Free(pointer)
+#endif
+
/// Macro to override the new and delete functions
#define JPH_OVERRIDE_NEW_DELETE \
- JPH_INLINE void *operator new (size_t inCount) { return JPH::Allocate(inCount); } \
- JPH_INLINE void operator delete (void *inPointer) noexcept { JPH::Free(inPointer); } \
- JPH_INLINE void *operator new[] (size_t inCount) { return JPH::Allocate(inCount); } \
- JPH_INLINE void operator delete[] (void *inPointer) noexcept { JPH::Free(inPointer); } \
+ JPH_INLINE void *operator new (size_t inCount) { return JPH_INTERNAL_DEFAULT_ALLOCATE(inCount); } \
+ JPH_INLINE void operator delete (void *inPointer) noexcept { JPH_INTERNAL_DEFAULT_FREE(inPointer); } \
+ JPH_INLINE void *operator new[] (size_t inCount) { return JPH_INTERNAL_DEFAULT_ALLOCATE(inCount); } \
+ JPH_INLINE void operator delete[] (void *inPointer) noexcept { JPH_INTERNAL_DEFAULT_FREE(inPointer); } \
JPH_INLINE void *operator new (size_t inCount, std::align_val_t inAlignment) { return JPH::AlignedAllocate(inCount, static_cast<size_t>(inAlignment)); } \
JPH_INLINE void operator delete (void *inPointer, [[maybe_unused]] std::align_val_t inAlignment) noexcept { JPH::AlignedFree(inPointer); } \
JPH_INLINE void *operator new[] (size_t inCount, std::align_val_t inAlignment) { return JPH::AlignedAllocate(inCount, static_cast<size_t>(inAlignment)); } \
| diff --git a/thirdparty/jolt_physics/Jolt/Core/Memory.h b/thirdparty/jolt_physics/Jolt/Core/Memory.h
index b5f318db1cfb..4f3dbc7d1326 100644
--- a/thirdparty/jolt_physics/Jolt/Core/Memory.h
+++ b/thirdparty/jolt_physics/Jolt/Core/Memory.h
@@ -27,12 +27,24 @@ JPH_EXPORT extern AlignedFreeFunction AlignedFree;
/// Register platform default allocation / free functions
JPH_EXPORT void RegisterDefaultAllocator();
+// 32-bit MinGW g++ doesn't call the correct overload for the new operator when a type is 16 bytes aligned.
+// It uses the non-aligned version, which on 32 bit platforms usually returns an 8 byte aligned block.
+// We therefore default to 16 byte aligned allocations when the regular new operator is used.
+// See: https://github.com/godotengine/godot/issues/105455#issuecomment-2824311547
+#if defined(JPH_COMPILER_MINGW) && JPH_CPU_ADDRESS_BITS == 32
+ #define JPH_INTERNAL_DEFAULT_ALLOCATE(size) JPH::AlignedAllocate(size, 16)
+ #define JPH_INTERNAL_DEFAULT_FREE(pointer) JPH::AlignedFree(pointer)
+#else
+ #define JPH_INTERNAL_DEFAULT_ALLOCATE(size) JPH::Allocate(size)
+#endif
+
/// Macro to override the new and delete functions
#define JPH_OVERRIDE_NEW_DELETE \
- JPH_INLINE void *operator new (size_t inCount) { return JPH::Allocate(inCount); } \
- JPH_INLINE void operator delete (void *inPointer) noexcept { JPH::Free(inPointer); } \
- JPH_INLINE void *operator new[] (size_t inCount) { return JPH::Allocate(inCount); } \
- JPH_INLINE void operator delete[] (void *inPointer) noexcept { JPH::Free(inPointer); } \
+ JPH_INLINE void *operator new (size_t inCount) { return JPH_INTERNAL_DEFAULT_ALLOCATE(inCount); } \
+ JPH_INLINE void operator delete (void *inPointer) noexcept { JPH_INTERNAL_DEFAULT_FREE(inPointer); } \
+ JPH_INLINE void *operator new[] (size_t inCount) { return JPH_INTERNAL_DEFAULT_ALLOCATE(inCount); } \
+ JPH_INLINE void operator delete[] (void *inPointer) noexcept { JPH_INTERNAL_DEFAULT_FREE(inPointer); } \
JPH_INLINE void *operator new (size_t inCount, std::align_val_t inAlignment) { return JPH::AlignedAllocate(inCount, static_cast<size_t>(inAlignment)); } \
JPH_INLINE void operator delete (void *inPointer, [[maybe_unused]] std::align_val_t inAlignment) noexcept { JPH::AlignedFree(inPointer); } \
JPH_INLINE void *operator new[] (size_t inCount, std::align_val_t inAlignment) { return JPH::AlignedAllocate(inCount, static_cast<size_t>(inAlignment)); } \ | [
"+\t#define JPH_INTERNAL_DEFAULT_FREE(pointer) JPH::Free(pointer)"
] | [
17
] | {
"additions": 16,
"author": "jrouwe",
"deletions": 4,
"html_url": "https://github.com/godotengine/godot/pull/105696",
"issue_id": 105696,
"merged_at": "2025-04-24T14:14:24Z",
"omission_probability": 0.1,
"pr_number": 105696,
"repo": "godotengine/godot",
"title": "Jolt: 32-bit MinGW g++ doesn't call the correct overload for the new operator when a type is 16 bytes aligned.",
"total_changes": 20
} |
718 | diff --git a/main/main.cpp b/main/main.cpp
index 487addc344be..f0a48d8d39e6 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -3348,14 +3348,6 @@ Error Main::setup2(bool p_show_boot_logo) {
rendering_server->set_print_gpu_profile(true);
}
- if (Engine::get_singleton()->get_write_movie_path() != String()) {
- movie_writer = MovieWriter::find_writer_for_file(Engine::get_singleton()->get_write_movie_path());
- if (movie_writer == nullptr) {
- ERR_PRINT("Can't find movie writer for file type, aborting: " + Engine::get_singleton()->get_write_movie_path());
- Engine::get_singleton()->set_write_movie_path(String());
- }
- }
-
OS::get_singleton()->benchmark_end_measure("Servers", "Rendering");
}
@@ -3579,6 +3571,16 @@ Error Main::setup2(bool p_show_boot_logo) {
GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
OS::get_singleton()->benchmark_end_measure("Scene", "Modules and Extensions");
+
+ // We need to initialize the movie writer here in case
+ // one of the user-provided GDExtensions subclasses MovieWriter.
+ if (Engine::get_singleton()->get_write_movie_path() != String()) {
+ movie_writer = MovieWriter::find_writer_for_file(Engine::get_singleton()->get_write_movie_path());
+ if (movie_writer == nullptr) {
+ ERR_PRINT("Can't find movie writer for file type, aborting: " + Engine::get_singleton()->get_write_movie_path());
+ Engine::get_singleton()->set_write_movie_path(String());
+ }
+ }
}
PackedStringArray extensions;
| diff --git a/main/main.cpp b/main/main.cpp
index 487addc344be..f0a48d8d39e6 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -3348,14 +3348,6 @@ Error Main::setup2(bool p_show_boot_logo) {
rendering_server->set_print_gpu_profile(true);
}
- if (movie_writer == nullptr) {
- ERR_PRINT("Can't find movie writer for file type, aborting: " + Engine::get_singleton()->get_write_movie_path());
- Engine::get_singleton()->set_write_movie_path(String());
- }
- }
-
OS::get_singleton()->benchmark_end_measure("Servers", "Rendering");
@@ -3579,6 +3571,16 @@ Error Main::setup2(bool p_show_boot_logo) {
GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
OS::get_singleton()->benchmark_end_measure("Scene", "Modules and Extensions");
+
+ // We need to initialize the movie writer here in case
+ // one of the user-provided GDExtensions subclasses MovieWriter.
+ if (Engine::get_singleton()->get_write_movie_path() != String()) {
+ movie_writer = MovieWriter::find_writer_for_file(Engine::get_singleton()->get_write_movie_path());
+ ERR_PRINT("Can't find movie writer for file type, aborting: " + Engine::get_singleton()->get_write_movie_path());
+ Engine::get_singleton()->set_write_movie_path(String());
+ }
+ }
PackedStringArray extensions; | [
"-\t\tif (Engine::get_singleton()->get_write_movie_path() != String()) {",
"-\t\t\tmovie_writer = MovieWriter::find_writer_for_file(Engine::get_singleton()->get_write_movie_path());",
"+\t\t\tif (movie_writer == nullptr) {"
] | [
8,
9,
28
] | {
"additions": 10,
"author": "mobile-bungalow",
"deletions": 8,
"html_url": "https://github.com/godotengine/godot/pull/96134",
"issue_id": 96134,
"merged_at": "2025-04-24T14:14:25Z",
"omission_probability": 0.1,
"pr_number": 96134,
"repo": "godotengine/godot",
"title": "`MovieWriter` extension support",
"total_changes": 18
} |
719 | diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml
index 05715749aafe..69dc6d698b52 100644
--- a/doc/classes/OS.xml
+++ b/doc/classes/OS.xml
@@ -294,7 +294,7 @@
<return type="PackedStringArray" />
<description>
On Android devices: Returns the list of dangerous permissions that have been granted.
- On macOS: Returns the list of user selected folders accessible to the application (sandboxed applications only). Use the native file dialog to request folder access permission.
+ On macOS: Returns the list of granted permissions and user selected folders accessible to the application (sandboxed applications only). Use the native file dialog to request folder access permission.
</description>
</method>
<method name="get_keycode_string" qualifiers="const">
@@ -755,8 +755,9 @@
The [param name] must be the full permission name. For example:
- [code]OS.request_permission("android.permission.READ_EXTERNAL_STORAGE")[/code]
- [code]OS.request_permission("android.permission.POST_NOTIFICATIONS")[/code]
- [b]Note:[/b] Permission must be checked during export.
- [b]Note:[/b] This method is only implemented on Android.
+ - [code]OS.request_permission("macos.permission.RECORD_SCREEN")[/code]
+ [b]Note:[/b] On Android, permission must be checked during export.
+ [b]Note:[/b] This method is implemented on Android and macOS.
</description>
</method>
<method name="request_permissions">
diff --git a/platform/macos/os_macos.h b/platform/macos/os_macos.h
index 0256147edcac..2bb4f9cba7ae 100644
--- a/platform/macos/os_macos.h
+++ b/platform/macos/os_macos.h
@@ -128,6 +128,7 @@ class OS_MacOS : public OS_Unix {
virtual String get_model_name() const override;
virtual bool is_sandboxed() const override;
+ virtual bool request_permission(const String &p_name) override;
virtual Vector<String> get_granted_permissions() const override;
virtual void revoke_granted_permissions() override;
diff --git a/platform/macos/os_macos.mm b/platform/macos/os_macos.mm
index 7aa68a724181..f205c29c3c3d 100644
--- a/platform/macos/os_macos.mm
+++ b/platform/macos/os_macos.mm
@@ -100,9 +100,35 @@
return has_environment("APP_SANDBOX_CONTAINER_ID");
}
+bool OS_MacOS::request_permission(const String &p_name) {
+ if (@available(macOS 10.15, *)) {
+ if (p_name == "macos.permission.RECORD_SCREEN") {
+ if (CGPreflightScreenCaptureAccess()) {
+ return true;
+ } else {
+ CGRequestScreenCaptureAccess();
+ return false;
+ }
+ }
+ } else {
+ if (p_name == "macos.permission.RECORD_SCREEN") {
+ return true;
+ }
+ }
+ return false;
+}
+
Vector<String> OS_MacOS::get_granted_permissions() const {
Vector<String> ret;
+ if (@available(macOS 10.15, *)) {
+ if (CGPreflightScreenCaptureAccess()) {
+ ret.push_back("macos.permission.RECORD_SCREEN");
+ }
+ } else {
+ ret.push_back("macos.permission.RECORD_SCREEN");
+ }
+
if (is_sandboxed()) {
NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
for (id bookmark in bookmarks) {
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index af891ba4830a..cd6eb2641d0a 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -38,6 +38,7 @@
#include "scene/gui/grid_container.h"
#include "scene/gui/label.h"
#include "scene/gui/line_edit.h"
+#include "scene/gui/link_button.h"
#include "scene/gui/margin_container.h"
#include "scene/gui/menu_button.h"
#include "scene/gui/panel.h"
@@ -68,6 +69,14 @@ void ColorPicker::_notification(int p_what) {
_update_color();
} break;
+#ifdef MACOS_ENABLED
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ if (is_visible_in_tree()) {
+ perm_hb->set_visible(!OS::get_singleton()->get_granted_permissions().has("macos.permission.RECORD_SCREEN"));
+ }
+ } break;
+#endif
+
case NOTIFICATION_READY: {
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_NATIVE_COLOR_PICKER)) {
btn_pick->set_accessibility_name(ETR("Pick Color From Screen"));
@@ -2215,6 +2224,23 @@ ColorPicker::ColorPicker() {
btn_add_preset->set_accessibility_name(ETR("Add Preset"));
btn_add_preset->connect(SceneStringName(pressed), callable_mp(this, &ColorPicker::_add_preset_pressed));
preset_container->add_child(btn_add_preset);
+
+ perm_hb = memnew(HBoxContainer);
+ perm_hb->set_alignment(BoxContainer::ALIGNMENT_CENTER);
+
+ LinkButton *perm_link = memnew(LinkButton);
+ perm_link->set_text(ETR("Screen Recording permission missing!"));
+ perm_link->set_tooltip_text(ETR("Screen Recording permission is required to pick colors from the other application windows.\nClick here to request access..."));
+ perm_link->connect(SceneStringName(pressed), callable_mp(this, &ColorPicker::_req_permission));
+ perm_hb->add_child(perm_link);
+ real_vbox->add_child(perm_hb);
+ perm_hb->set_visible(false);
+}
+
+void ColorPicker::_req_permission() {
+#ifdef MACOS_ENABLED
+ OS::get_singleton()->request_permission("macos.permission.RECORD_SCREEN");
+#endif
}
ColorPicker::~ColorPicker() {
diff --git a/scene/gui/color_picker.h b/scene/gui/color_picker.h
index 78fd5a61cb2c..2257e8bf0443 100644
--- a/scene/gui/color_picker.h
+++ b/scene/gui/color_picker.h
@@ -186,6 +186,9 @@ class ColorPicker : public VBoxContainer {
Ref<ButtonGroup> preset_group;
Ref<ButtonGroup> recent_preset_group;
+ HBoxContainer *perm_hb = nullptr;
+ void _req_permission();
+
#ifdef TOOLS_ENABLED
Callable quick_open_callback;
Callable palette_saved_callback;
| diff --git a/doc/classes/OS.xml b/doc/classes/OS.xml
index 05715749aafe..69dc6d698b52 100644
--- a/doc/classes/OS.xml
+++ b/doc/classes/OS.xml
@@ -294,7 +294,7 @@
<return type="PackedStringArray" />
<description>
On Android devices: Returns the list of dangerous permissions that have been granted.
- On macOS: Returns the list of user selected folders accessible to the application (sandboxed applications only). Use the native file dialog to request folder access permission.
+ On macOS: Returns the list of granted permissions and user selected folders accessible to the application (sandboxed applications only). Use the native file dialog to request folder access permission.
<method name="get_keycode_string" qualifiers="const">
@@ -755,8 +755,9 @@
The [param name] must be the full permission name. For example:
- [code]OS.request_permission("android.permission.READ_EXTERNAL_STORAGE")[/code]
- [code]OS.request_permission("android.permission.POST_NOTIFICATIONS")[/code]
- [b]Note:[/b] Permission must be checked during export.
- [b]Note:[/b] This method is only implemented on Android.
+ [b]Note:[/b] On Android, permission must be checked during export.
+ [b]Note:[/b] This method is implemented on Android and macOS.
<method name="request_permissions">
diff --git a/platform/macos/os_macos.h b/platform/macos/os_macos.h
index 0256147edcac..2bb4f9cba7ae 100644
--- a/platform/macos/os_macos.h
+++ b/platform/macos/os_macos.h
@@ -128,6 +128,7 @@ class OS_MacOS : public OS_Unix {
virtual String get_model_name() const override;
virtual bool is_sandboxed() const override;
virtual Vector<String> get_granted_permissions() const override;
virtual void revoke_granted_permissions() override;
diff --git a/platform/macos/os_macos.mm b/platform/macos/os_macos.mm
index 7aa68a724181..f205c29c3c3d 100644
--- a/platform/macos/os_macos.mm
+++ b/platform/macos/os_macos.mm
@@ -100,9 +100,35 @@
return has_environment("APP_SANDBOX_CONTAINER_ID");
+bool OS_MacOS::request_permission(const String &p_name) {
+ if (CGPreflightScreenCaptureAccess()) {
+ return true;
+ } else {
+ CGRequestScreenCaptureAccess();
+ return false;
+ return true;
+ return false;
Vector<String> OS_MacOS::get_granted_permissions() const {
Vector<String> ret;
+ if (CGPreflightScreenCaptureAccess()) {
+ ret.push_back("macos.permission.RECORD_SCREEN");
if (is_sandboxed()) {
NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
for (id bookmark in bookmarks) {
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index af891ba4830a..cd6eb2641d0a 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -38,6 +38,7 @@
#include "scene/gui/grid_container.h"
#include "scene/gui/label.h"
#include "scene/gui/line_edit.h"
+#include "scene/gui/link_button.h"
#include "scene/gui/margin_container.h"
#include "scene/gui/menu_button.h"
#include "scene/gui/panel.h"
@@ -68,6 +69,14 @@ void ColorPicker::_notification(int p_what) {
_update_color();
} break;
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ if (is_visible_in_tree()) {
+ perm_hb->set_visible(!OS::get_singleton()->get_granted_permissions().has("macos.permission.RECORD_SCREEN"));
+ } break;
case NOTIFICATION_READY: {
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_NATIVE_COLOR_PICKER)) {
btn_pick->set_accessibility_name(ETR("Pick Color From Screen"));
@@ -2215,6 +2224,23 @@ ColorPicker::ColorPicker() {
btn_add_preset->set_accessibility_name(ETR("Add Preset"));
btn_add_preset->connect(SceneStringName(pressed), callable_mp(this, &ColorPicker::_add_preset_pressed));
preset_container->add_child(btn_add_preset);
+ perm_hb = memnew(HBoxContainer);
+ perm_hb->set_alignment(BoxContainer::ALIGNMENT_CENTER);
+ LinkButton *perm_link = memnew(LinkButton);
+ perm_link->set_text(ETR("Screen Recording permission missing!"));
+ perm_link->set_tooltip_text(ETR("Screen Recording permission is required to pick colors from the other application windows.\nClick here to request access..."));
+ perm_link->connect(SceneStringName(pressed), callable_mp(this, &ColorPicker::_req_permission));
+ real_vbox->add_child(perm_hb);
+ perm_hb->set_visible(false);
+void ColorPicker::_req_permission() {
ColorPicker::~ColorPicker() {
diff --git a/scene/gui/color_picker.h b/scene/gui/color_picker.h
index 78fd5a61cb2c..2257e8bf0443 100644
--- a/scene/gui/color_picker.h
+++ b/scene/gui/color_picker.h
@@ -186,6 +186,9 @@ class ColorPicker : public VBoxContainer {
Ref<ButtonGroup> preset_group;
Ref<ButtonGroup> recent_preset_group;
+ HBoxContainer *perm_hb = nullptr;
+ void _req_permission();
#ifdef TOOLS_ENABLED
Callable quick_open_callback;
Callable palette_saved_callback; | [
"+\t\t\t\t- [code]OS.request_permission(\"macos.permission.RECORD_SCREEN\")[/code]",
"+\tvirtual bool request_permission(const String &p_name) override;",
"+\t\tret.push_back(\"macos.permission.RECORD_SCREEN\");",
"+\tperm_hb->add_child(perm_link);",
"+\tOS::get_singleton()->request_permission(\"macos.permission.RECORD_SCREEN\");"
] | [
19,
33,
71,
116,
123
] | {
"additions": 60,
"author": "bruvzg",
"deletions": 3,
"html_url": "https://github.com/godotengine/godot/pull/105507",
"issue_id": 105507,
"merged_at": "2025-04-24T14:14:24Z",
"omission_probability": 0.1,
"pr_number": 105507,
"repo": "godotengine/godot",
"title": "[ColorPicker, macOS] Add link to request required screen recording permission.",
"total_changes": 63
} |
720 | diff --git a/core/math/a_star.cpp b/core/math/a_star.cpp
index 9b6717c693de..3e537ae18097 100644
--- a/core/math/a_star.cpp
+++ b/core/math/a_star.cpp
@@ -260,7 +260,6 @@ int64_t AStar3D::get_point_capacity() const {
void AStar3D::reserve_space(int64_t p_num_nodes) {
ERR_FAIL_COND_MSG(p_num_nodes <= 0, vformat("New capacity must be greater than 0, new was: %d.", p_num_nodes));
- ERR_FAIL_COND_MSG((uint32_t)p_num_nodes < points.get_capacity(), vformat("New capacity must be greater than current capacity: %d, new was: %d.", points.get_capacity(), p_num_nodes));
points.reserve(p_num_nodes);
}
diff --git a/core/string/string_buffer.h b/core/string/string_buffer.h
index 5a4e66f51eab..6f648b3eae64 100644
--- a/core/string/string_buffer.h
+++ b/core/string/string_buffer.h
@@ -117,7 +117,8 @@ StringBuffer<SHORT_BUFFER_SIZE> &StringBuffer<SHORT_BUFFER_SIZE>::append(const c
template <int SHORT_BUFFER_SIZE>
StringBuffer<SHORT_BUFFER_SIZE> &StringBuffer<SHORT_BUFFER_SIZE>::reserve(int p_size) {
- if (p_size < SHORT_BUFFER_SIZE || p_size < buffer.size() || !p_size) {
+ ERR_FAIL_COND_V_MSG(p_size < length(), *this, "reserve() called with a capacity smaller than the current size. This is likely a mistake.");
+ if (p_size <= SHORT_BUFFER_SIZE || p_size <= buffer.size()) {
return *this;
}
diff --git a/core/templates/a_hash_map.h b/core/templates/a_hash_map.h
index b71db3dc4cfc..e603d0aa5f27 100644
--- a/core/templates/a_hash_map.h
+++ b/core/templates/a_hash_map.h
@@ -414,12 +414,15 @@ class AHashMap {
// Reserves space for a number of elements, useful to avoid many resizes and rehashes.
// If adding a known (possibly large) number of elements at once, must be larger than old capacity.
void reserve(uint32_t p_new_capacity) {
- ERR_FAIL_COND_MSG(p_new_capacity < get_capacity(), "It is impossible to reserve less capacity than is currently available.");
+ ERR_FAIL_COND_MSG(p_new_capacity < size(), "reserve() called with a capacity smaller than the current size. This is likely a mistake.");
if (elements == nullptr) {
capacity = MAX(4u, p_new_capacity);
capacity = next_power_of_2(capacity) - 1;
return; // Unallocated yet.
}
+ if (p_new_capacity <= get_capacity()) {
+ return;
+ }
_resize_and_rehash(p_new_capacity);
}
@@ -665,9 +668,7 @@ class AHashMap {
}
AHashMap(const HashMap<TKey, TValue> &p_other) {
- if (p_other.size() > get_capacity()) {
- reserve(p_other.size());
- }
+ reserve(p_other.size());
for (const KeyValue<TKey, TValue> &E : p_other) {
uint32_t hash = _hash(E.key);
_insert_element(E.key, E.value, hash);
@@ -686,9 +687,7 @@ class AHashMap {
void operator=(const HashMap<TKey, TValue> &p_other) {
reset();
- if (p_other.size() > get_capacity()) {
- reserve(p_other.size());
- }
+ reserve(p_other.size());
for (const KeyValue<TKey, TValue> &E : p_other) {
uint32_t hash = _hash(E.key);
_insert_element(E.key, E.value, hash);
@@ -705,9 +704,7 @@ class AHashMap {
}
AHashMap(std::initializer_list<KeyValue<TKey, TValue>> p_init) {
- if (p_init.size() > get_capacity()) {
- reserve(p_init.size());
- }
+ reserve(p_init.size());
for (const KeyValue<TKey, TValue> &E : p_init) {
insert(E.key, E.value);
}
diff --git a/core/templates/hash_map.h b/core/templates/hash_map.h
index 4dc6baf47b10..eaf58594875b 100644
--- a/core/templates/hash_map.h
+++ b/core/templates/hash_map.h
@@ -432,6 +432,7 @@ class HashMap {
// Reserves space for a number of elements, useful to avoid many resizes and rehashes.
// If adding a known (possibly large) number of elements at once, must be larger than old capacity.
void reserve(uint32_t p_new_capacity) {
+ ERR_FAIL_COND_MSG(p_new_capacity < size(), "reserve() called with a capacity smaller than the current size. This is likely a mistake.");
uint32_t new_index = capacity_index;
while (hash_table_size_primes[new_index] < p_new_capacity) {
diff --git a/core/templates/hash_set.h b/core/templates/hash_set.h
index 14632a3b88d8..b2982f686004 100644
--- a/core/templates/hash_set.h
+++ b/core/templates/hash_set.h
@@ -294,6 +294,7 @@ class HashSet {
// Reserves space for a number of elements, useful to avoid many resizes and rehashes.
// If adding a known (possibly large) number of elements at once, must be larger than old capacity.
void reserve(uint32_t p_new_capacity) {
+ ERR_FAIL_COND_MSG(p_new_capacity < size(), "reserve() called with a capacity smaller than the current size. This is likely a mistake.");
uint32_t new_index = capacity_index;
while (hash_table_size_primes[new_index] < p_new_capacity) {
diff --git a/core/templates/local_vector.h b/core/templates/local_vector.h
index 3983deea8860..547006d1915d 100644
--- a/core/templates/local_vector.h
+++ b/core/templates/local_vector.h
@@ -144,6 +144,7 @@ class LocalVector {
_FORCE_INLINE_ bool is_empty() const { return count == 0; }
_FORCE_INLINE_ U get_capacity() const { return capacity; }
void reserve(U p_size) {
+ ERR_FAIL_COND_MSG(p_size < size(), "reserve() called with a capacity smaller than the current size. This is likely a mistake.");
if (p_size > capacity) {
if (tight) {
capacity = p_size;
diff --git a/core/templates/oa_hash_map.h b/core/templates/oa_hash_map.h
index 3aedeb695e48..18487e107faf 100644
--- a/core/templates/oa_hash_map.h
+++ b/core/templates/oa_hash_map.h
@@ -301,7 +301,10 @@ class OAHashMap {
* capacity.
**/
void reserve(uint32_t p_new_capacity) {
- ERR_FAIL_COND(p_new_capacity < capacity);
+ ERR_FAIL_COND_MSG(p_new_capacity < get_num_elements(), "reserve() called with a capacity smaller than the current size. This is likely a mistake.");
+ if (p_new_capacity <= capacity) {
+ return;
+ }
_resize_and_rehash(p_new_capacity);
}
| diff --git a/core/math/a_star.cpp b/core/math/a_star.cpp
index 9b6717c693de..3e537ae18097 100644
--- a/core/math/a_star.cpp
+++ b/core/math/a_star.cpp
@@ -260,7 +260,6 @@ int64_t AStar3D::get_point_capacity() const {
void AStar3D::reserve_space(int64_t p_num_nodes) {
ERR_FAIL_COND_MSG(p_num_nodes <= 0, vformat("New capacity must be greater than 0, new was: %d.", p_num_nodes));
- ERR_FAIL_COND_MSG((uint32_t)p_num_nodes < points.get_capacity(), vformat("New capacity must be greater than current capacity: %d, new was: %d.", points.get_capacity(), p_num_nodes));
points.reserve(p_num_nodes);
}
diff --git a/core/string/string_buffer.h b/core/string/string_buffer.h
index 5a4e66f51eab..6f648b3eae64 100644
--- a/core/string/string_buffer.h
+++ b/core/string/string_buffer.h
@@ -117,7 +117,8 @@ StringBuffer<SHORT_BUFFER_SIZE> &StringBuffer<SHORT_BUFFER_SIZE>::append(const c
template <int SHORT_BUFFER_SIZE>
StringBuffer<SHORT_BUFFER_SIZE> &StringBuffer<SHORT_BUFFER_SIZE>::reserve(int p_size) {
- if (p_size < SHORT_BUFFER_SIZE || p_size < buffer.size() || !p_size) {
+ if (p_size <= SHORT_BUFFER_SIZE || p_size <= buffer.size()) {
return *this;
diff --git a/core/templates/a_hash_map.h b/core/templates/a_hash_map.h
index b71db3dc4cfc..e603d0aa5f27 100644
--- a/core/templates/a_hash_map.h
+++ b/core/templates/a_hash_map.h
@@ -414,12 +414,15 @@ class AHashMap {
if (elements == nullptr) {
capacity = MAX(4u, p_new_capacity);
capacity = next_power_of_2(capacity) - 1;
return; // Unallocated yet.
+ if (p_new_capacity <= get_capacity()) {
@@ -665,9 +668,7 @@ class AHashMap {
AHashMap(const HashMap<TKey, TValue> &p_other) {
@@ -686,9 +687,7 @@ class AHashMap {
void operator=(const HashMap<TKey, TValue> &p_other) {
reset();
@@ -705,9 +704,7 @@ class AHashMap {
AHashMap(std::initializer_list<KeyValue<TKey, TValue>> p_init) {
- if (p_init.size() > get_capacity()) {
- reserve(p_init.size());
+ reserve(p_init.size());
for (const KeyValue<TKey, TValue> &E : p_init) {
insert(E.key, E.value);
diff --git a/core/templates/hash_map.h b/core/templates/hash_map.h
index 4dc6baf47b10..eaf58594875b 100644
--- a/core/templates/hash_map.h
+++ b/core/templates/hash_map.h
@@ -432,6 +432,7 @@ class HashMap {
diff --git a/core/templates/hash_set.h b/core/templates/hash_set.h
index 14632a3b88d8..b2982f686004 100644
--- a/core/templates/hash_set.h
+++ b/core/templates/hash_set.h
@@ -294,6 +294,7 @@ class HashSet {
diff --git a/core/templates/local_vector.h b/core/templates/local_vector.h
index 3983deea8860..547006d1915d 100644
--- a/core/templates/local_vector.h
+++ b/core/templates/local_vector.h
@@ -144,6 +144,7 @@ class LocalVector {
_FORCE_INLINE_ bool is_empty() const { return count == 0; }
_FORCE_INLINE_ U get_capacity() const { return capacity; }
void reserve(U p_size) {
if (p_size > capacity) {
if (tight) {
capacity = p_size;
diff --git a/core/templates/oa_hash_map.h b/core/templates/oa_hash_map.h
index 3aedeb695e48..18487e107faf 100644
--- a/core/templates/oa_hash_map.h
+++ b/core/templates/oa_hash_map.h
@@ -301,7 +301,10 @@ class OAHashMap {
* capacity.
**/
- ERR_FAIL_COND(p_new_capacity < capacity);
+ ERR_FAIL_COND_MSG(p_new_capacity < get_num_elements(), "reserve() called with a capacity smaller than the current size. This is likely a mistake.");
+ if (p_new_capacity <= capacity) { | [
"+\tERR_FAIL_COND_V_MSG(p_size < length(), *this, \"reserve() called with a capacity smaller than the current size. This is likely a mistake.\");",
"-\t\tERR_FAIL_COND_MSG(p_new_capacity < get_capacity(), \"It is impossible to reserve less capacity than is currently available.\");",
"+\t\tERR_FAIL_COND_MSG(p_size < size(), \"reserve() called with a capacity smaller than the current size. This is likely a mistake.\");"
] | [
21,
34,
112
] | {
"additions": 16,
"author": "Ivorforce",
"deletions": 13,
"html_url": "https://github.com/godotengine/godot/pull/105278",
"issue_id": 105278,
"merged_at": "2025-04-23T17:11:45Z",
"omission_probability": 0.1,
"pr_number": 105278,
"repo": "godotengine/godot",
"title": "Smoke test: Log an error if `reserve()` is called with fewer elements than `size()`",
"total_changes": 29
} |
721 | diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp
index 869faa981eee..42b6c3c1f460 100644
--- a/core/io/resource_loader.cpp
+++ b/core/io/resource_loader.cpp
@@ -1274,44 +1274,39 @@ String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_rem
}
}
- if (path_remaps.has(new_path)) {
- new_path = path_remaps[new_path];
- } else {
- // Try file remap.
- // Usually, there's no remap file and FileAccess::exists() is faster than FileAccess::open().
- new_path = ResourceUID::ensure_path(new_path);
- if (FileAccess::exists(new_path + ".remap")) {
- Error err;
- Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
- if (f.is_valid()) {
- VariantParser::StreamFile stream;
- stream.f = f;
-
- String assign;
- Variant value;
- VariantParser::Tag next_tag;
-
- int lines = 0;
- String error_text;
- while (true) {
- assign = Variant();
- next_tag.fields.clear();
- next_tag.name = String();
-
- err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
- if (err == ERR_FILE_EOF) {
- break;
- } else if (err != OK) {
- ERR_PRINT(vformat("Parse error: %s.remap:%d error: %s.", p_path, lines, error_text));
- break;
- }
+ // Usually, there's no remap file and FileAccess::exists() is faster than FileAccess::open().
+ new_path = ResourceUID::ensure_path(new_path);
+ if (FileAccess::exists(new_path + ".remap")) {
+ Error err;
+ Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
+ if (f.is_valid()) {
+ VariantParser::StreamFile stream;
+ stream.f = f;
+
+ String assign;
+ Variant value;
+ VariantParser::Tag next_tag;
+
+ int lines = 0;
+ String error_text;
+ while (true) {
+ assign = Variant();
+ next_tag.fields.clear();
+ next_tag.name = String();
+
+ err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
+ if (err == ERR_FILE_EOF) {
+ break;
+ } else if (err != OK) {
+ ERR_PRINT(vformat("Parse error: %s.remap:%d error: %s.", p_path, lines, error_text));
+ break;
+ }
- if (assign == "path") {
- new_path = value;
- break;
- } else if (next_tag.name != "remap") {
- break;
- }
+ if (assign == "path") {
+ new_path = value;
+ break;
+ } else if (next_tag.name != "remap") {
+ break;
}
}
}
@@ -1419,25 +1414,6 @@ void ResourceLoader::clear_thread_load_tasks() {
cleaning_tasks = false;
}
-void ResourceLoader::load_path_remaps() {
- if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
- return;
- }
-
- Vector<String> remaps = GLOBAL_GET("path_remap/remapped_paths");
- int rc = remaps.size();
- ERR_FAIL_COND(rc & 1); //must be even
- const String *r = remaps.ptr();
-
- for (int i = 0; i < rc; i += 2) {
- path_remaps[r[i]] = r[i + 1];
- }
-}
-
-void ResourceLoader::clear_path_remaps() {
- path_remaps.clear();
-}
-
void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
_loaded_callback = p_callback;
}
@@ -1602,6 +1578,5 @@ HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
SelfList<Resource>::List ResourceLoader::remapped_list;
HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
-HashMap<String, String> ResourceLoader::path_remaps;
ResourceLoaderImport ResourceLoader::import = nullptr;
diff --git a/core/io/resource_loader.h b/core/io/resource_loader.h
index 189f000ee609..d2873863501b 100644
--- a/core/io/resource_loader.h
+++ b/core/io/resource_loader.h
@@ -159,7 +159,6 @@ class ResourceLoader {
static bool abort_on_missing_resource;
static bool create_missing_resources_if_class_unavailable;
static HashMap<String, Vector<String>> translation_remaps;
- static HashMap<String, String> path_remaps;
static String _path_remap(const String &p_path, bool *r_translation_remapped = nullptr);
friend class Resource;
@@ -289,9 +288,6 @@ class ResourceLoader {
static String path_remap(const String &p_path);
static String import_remap(const String &p_path);
- static void load_path_remaps();
- static void clear_path_remaps();
-
static void reload_translation_remaps();
static void load_translation_remaps();
static void clear_translation_remaps();
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index d4839bb37066..ff506b8baef5 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -7142,7 +7142,6 @@ EditorNode::EditorNode() {
SceneState::set_disable_placeholders(true);
ResourceLoader::clear_translation_remaps(); // Using no remaps if in editor.
- ResourceLoader::clear_path_remaps();
ResourceLoader::set_create_missing_resources_if_class_unavailable(true);
EditorPropertyNameProcessor *epnp = memnew(EditorPropertyNameProcessor);
diff --git a/editor/export/editor_export_platform.cpp b/editor/export/editor_export_platform.cpp
index 6f41c1ecf46b..c7310e90dff5 100644
--- a/editor/export/editor_export_platform.cpp
+++ b/editor/export/editor_export_platform.cpp
@@ -1542,28 +1542,22 @@ Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset> &
custom_list.append_array(export_plugins[i]->_get_export_features(Ref<EditorExportPlatform>(this), p_debug));
}
- ProjectSettings::CustomMap custom_map = get_custom_project_settings(p_preset);
if (path_remaps.size()) {
- if (true) { //new remap mode, use always as it's friendlier with multiple .pck exports
- for (int i = 0; i < path_remaps.size(); i += 2) {
- const String &from = path_remaps[i];
- const String &to = path_remaps[i + 1];
- String remap_file = "[remap]\n\npath=\"" + to.c_escape() + "\"\n";
- CharString utf8 = remap_file.utf8();
- Vector<uint8_t> new_file;
- new_file.resize(utf8.length());
- for (int j = 0; j < utf8.length(); j++) {
- new_file.write[j] = utf8[j];
- }
+ for (int i = 0; i < path_remaps.size(); i += 2) {
+ const String &from = path_remaps[i];
+ const String &to = path_remaps[i + 1];
+ String remap_file = "[remap]\n\npath=\"" + to.c_escape() + "\"\n";
+ CharString utf8 = remap_file.utf8();
+ Vector<uint8_t> new_file;
+ new_file.resize(utf8.length());
+ for (int j = 0; j < utf8.length(); j++) {
+ new_file.write[j] = utf8[j];
+ }
- err = save_proxy.save_file(p_udata, from + ".remap", new_file, idx, total, enc_in_filters, enc_ex_filters, key, seed);
- if (err != OK) {
- return err;
- }
+ err = save_proxy.save_file(p_udata, from + ".remap", new_file, idx, total, enc_in_filters, enc_ex_filters, key, seed);
+ if (err != OK) {
+ return err;
}
- } else {
- //old remap mode, will still work, but it's unused because it's not multiple pck export friendly
- custom_map["path_remap/remapped_paths"] = path_remaps;
}
}
@@ -1595,6 +1589,7 @@ Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset> &
String config_file = "project.binary";
String engine_cfb = EditorPaths::get_singleton()->get_temp_dir().path_join("tmp" + config_file);
+ ProjectSettings::CustomMap custom_map = get_custom_project_settings(p_preset);
ProjectSettings::get_singleton()->save_custom(engine_cfb, custom_map, custom_list);
Vector<uint8_t> data = FileAccess::get_file_as_bytes(engine_cfb);
DirAccess::remove_file_or_error(engine_cfb);
diff --git a/main/main.cpp b/main/main.cpp
index 487addc344be..b699eb71ea47 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -759,8 +759,6 @@ Error Main::test_setup() {
translation_server->load_translations();
ResourceLoader::load_translation_remaps(); //load remaps for resources
- ResourceLoader::load_path_remaps();
-
// Initialize ThemeDB early so that scene types can register their theme items.
// Default theme will be initialized later, after modules and ScriptServer are ready.
initialize_theme_db();
@@ -3475,8 +3473,6 @@ Error Main::setup2(bool p_show_boot_logo) {
translation_server->load_translations();
ResourceLoader::load_translation_remaps(); //load remaps for resources
- ResourceLoader::load_path_remaps();
-
OS::get_singleton()->benchmark_end_measure("Startup", "Translations and Remaps");
}
@@ -4915,7 +4911,6 @@ void Main::cleanup(bool p_force) {
OS::get_singleton()->_local_clipboard = "";
ResourceLoader::clear_translation_remaps();
- ResourceLoader::clear_path_remaps();
WorkerThreadPool::get_singleton()->exit_languages_threads();
| diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp
index 869faa981eee..42b6c3c1f460 100644
--- a/core/io/resource_loader.cpp
+++ b/core/io/resource_loader.cpp
@@ -1274,44 +1274,39 @@ String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_rem
- if (path_remaps.has(new_path)) {
- new_path = path_remaps[new_path];
- } else {
- // Try file remap.
- // Usually, there's no remap file and FileAccess::exists() is faster than FileAccess::open().
- new_path = ResourceUID::ensure_path(new_path);
- if (FileAccess::exists(new_path + ".remap")) {
- Error err;
- Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
- VariantParser::StreamFile stream;
- stream.f = f;
- String assign;
- Variant value;
- VariantParser::Tag next_tag;
- int lines = 0;
- while (true) {
- assign = Variant();
- next_tag.fields.clear();
- next_tag.name = String();
- err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
- if (err == ERR_FILE_EOF) {
- } else if (err != OK) {
- ERR_PRINT(vformat("Parse error: %s.remap:%d error: %s.", p_path, lines, error_text));
+ if (FileAccess::exists(new_path + ".remap")) {
+ Error err;
+ if (f.is_valid()) {
+ VariantParser::StreamFile stream;
+ stream.f = f;
+ String assign;
+ Variant value;
+ VariantParser::Tag next_tag;
+ int lines = 0;
+ String error_text;
+ while (true) {
+ assign = Variant();
+ next_tag.fields.clear();
+ next_tag.name = String();
+ if (err == ERR_FILE_EOF) {
+ ERR_PRINT(vformat("Parse error: %s.remap:%d error: %s.", p_path, lines, error_text));
+ }
- if (assign == "path") {
- new_path = value;
- } else if (next_tag.name != "remap") {
+ if (assign == "path") {
+ new_path = value;
+ } else if (next_tag.name != "remap") {
}
@@ -1419,25 +1414,6 @@ void ResourceLoader::clear_thread_load_tasks() {
cleaning_tasks = false;
- int rc = remaps.size();
- ERR_FAIL_COND(rc & 1); //must be even
- const String *r = remaps.ptr();
- for (int i = 0; i < rc; i += 2) {
- path_remaps.clear();
void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
_loaded_callback = p_callback;
@@ -1602,6 +1578,5 @@ HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
SelfList<Resource>::List ResourceLoader::remapped_list;
HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
-HashMap<String, String> ResourceLoader::path_remaps;
ResourceLoaderImport ResourceLoader::import = nullptr;
diff --git a/core/io/resource_loader.h b/core/io/resource_loader.h
index 189f000ee609..d2873863501b 100644
--- a/core/io/resource_loader.h
+++ b/core/io/resource_loader.h
@@ -159,7 +159,6 @@ class ResourceLoader {
static bool abort_on_missing_resource;
static bool create_missing_resources_if_class_unavailable;
static HashMap<String, Vector<String>> translation_remaps;
- static HashMap<String, String> path_remaps;
static String _path_remap(const String &p_path, bool *r_translation_remapped = nullptr);
friend class Resource;
@@ -289,9 +288,6 @@ class ResourceLoader {
static String path_remap(const String &p_path);
static String import_remap(const String &p_path);
- static void load_path_remaps();
- static void clear_path_remaps();
static void reload_translation_remaps();
static void load_translation_remaps();
static void clear_translation_remaps();
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index d4839bb37066..ff506b8baef5 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -7142,7 +7142,6 @@ EditorNode::EditorNode() {
SceneState::set_disable_placeholders(true);
ResourceLoader::clear_translation_remaps(); // Using no remaps if in editor.
ResourceLoader::set_create_missing_resources_if_class_unavailable(true);
EditorPropertyNameProcessor *epnp = memnew(EditorPropertyNameProcessor);
diff --git a/editor/export/editor_export_platform.cpp b/editor/export/editor_export_platform.cpp
index 6f41c1ecf46b..c7310e90dff5 100644
--- a/editor/export/editor_export_platform.cpp
+++ b/editor/export/editor_export_platform.cpp
@@ -1542,28 +1542,22 @@ Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset> &
custom_list.append_array(export_plugins[i]->_get_export_features(Ref<EditorExportPlatform>(this), p_debug));
- ProjectSettings::CustomMap custom_map = get_custom_project_settings(p_preset);
if (path_remaps.size()) {
- if (true) { //new remap mode, use always as it's friendlier with multiple .pck exports
- for (int i = 0; i < path_remaps.size(); i += 2) {
- const String &from = path_remaps[i];
- const String &to = path_remaps[i + 1];
- String remap_file = "[remap]\n\npath=\"" + to.c_escape() + "\"\n";
- CharString utf8 = remap_file.utf8();
- Vector<uint8_t> new_file;
- new_file.resize(utf8.length());
- for (int j = 0; j < utf8.length(); j++) {
- new_file.write[j] = utf8[j];
+ for (int i = 0; i < path_remaps.size(); i += 2) {
+ const String &from = path_remaps[i];
+ const String &to = path_remaps[i + 1];
+ String remap_file = "[remap]\n\npath=\"" + to.c_escape() + "\"\n";
+ CharString utf8 = remap_file.utf8();
+ Vector<uint8_t> new_file;
+ new_file.resize(utf8.length());
+ for (int j = 0; j < utf8.length(); j++) {
+ new_file.write[j] = utf8[j];
+ }
- err = save_proxy.save_file(p_udata, from + ".remap", new_file, idx, total, enc_in_filters, enc_ex_filters, key, seed);
- if (err != OK) {
- return err;
+ err = save_proxy.save_file(p_udata, from + ".remap", new_file, idx, total, enc_in_filters, enc_ex_filters, key, seed);
+ if (err != OK) {
+ return err;
- } else {
- //old remap mode, will still work, but it's unused because it's not multiple pck export friendly
- custom_map["path_remap/remapped_paths"] = path_remaps;
@@ -1595,6 +1589,7 @@ Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset> &
String config_file = "project.binary";
String engine_cfb = EditorPaths::get_singleton()->get_temp_dir().path_join("tmp" + config_file);
+ ProjectSettings::CustomMap custom_map = get_custom_project_settings(p_preset);
ProjectSettings::get_singleton()->save_custom(engine_cfb, custom_map, custom_list);
Vector<uint8_t> data = FileAccess::get_file_as_bytes(engine_cfb);
DirAccess::remove_file_or_error(engine_cfb);
diff --git a/main/main.cpp b/main/main.cpp
index 487addc344be..b699eb71ea47 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -759,8 +759,6 @@ Error Main::test_setup() {
translation_server->load_translations();
ResourceLoader::load_translation_remaps(); //load remaps for resources
- ResourceLoader::load_path_remaps();
// Initialize ThemeDB early so that scene types can register their theme items.
// Default theme will be initialized later, after modules and ScriptServer are ready.
initialize_theme_db();
@@ -3475,8 +3473,6 @@ Error Main::setup2(bool p_show_boot_logo) {
translation_server->load_translations();
ResourceLoader::load_translation_remaps(); //load remaps for resources
- ResourceLoader::load_path_remaps();
OS::get_singleton()->benchmark_end_measure("Startup", "Translations and Remaps");
@@ -4915,7 +4911,6 @@ void Main::cleanup(bool p_force) {
OS::get_singleton()->_local_clipboard = "";
ResourceLoader::clear_translation_remaps();
WorkerThreadPool::get_singleton()->exit_languages_threads(); | [
"-\t\t\tif (f.is_valid()) {",
"-\t\t\t\tString error_text;",
"+\t// Usually, there's no remap file and FileAccess::exists() is faster than FileAccess::open().",
"+\tnew_path = ResourceUID::ensure_path(new_path);",
"+\t\tRef<FileAccess> f = FileAccess::open(new_path + \".remap\", FileAccess::READ, &err);",
"+\t\t\t\terr = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);",
"+\t\t\t\t} else if (err != OK) {",
"-void ResourceLoader::load_path_remaps() {",
"-\tif (!ProjectSettings::get_singleton()->has_setting(\"path_remap/remapped_paths\")) {",
"-\t\treturn;",
"-\tVector<String> remaps = GLOBAL_GET(\"path_remap/remapped_paths\");",
"-\t\tpath_remaps[r[i]] = r[i + 1];",
"-void ResourceLoader::clear_path_remaps() {"
] | [
17,
26,
39,
40,
43,
59,
62,
85,
86,
87,
90,
96,
100
] | {
"additions": 46,
"author": "RedMser",
"deletions": 86,
"html_url": "https://github.com/godotengine/godot/pull/91594",
"issue_id": 91594,
"merged_at": "2025-04-23T17:11:45Z",
"omission_probability": 0.1,
"pr_number": 91594,
"repo": "godotengine/godot",
"title": "Remove old path remaps system",
"total_changes": 132
} |
722 | diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp
index e5737df2ae5f..b54a821cd809 100644
--- a/platform/windows/os_windows.cpp
+++ b/platform/windows/os_windows.cpp
@@ -723,7 +723,7 @@ Vector<String> OS_Windows::get_video_adapter_driver_info() const {
BSTR object_name = SysAllocString(L"DriverName");
hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
SysFreeString(object_name);
- if (hr == S_OK) {
+ if (hr == S_OK && dn.vt == VT_BSTR) {
String d_name = String(V_BSTR(&dn));
if (d_name.is_empty()) {
object_name = SysAllocString(L"DriverProviderName");
@@ -739,8 +739,10 @@ Vector<String> OS_Windows::get_video_adapter_driver_info() const {
object_name = SysAllocString(L"DriverProviderName");
hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
SysFreeString(object_name);
- if (hr == S_OK) {
+ if (hr == S_OK && dn.vt == VT_BSTR) {
driver_name = String(V_BSTR(&dn));
+ } else {
+ driver_name = "Unknown";
}
}
@@ -749,8 +751,10 @@ Vector<String> OS_Windows::get_video_adapter_driver_info() const {
object_name = SysAllocString(L"DriverVersion");
hr = pnpSDriverObject[0]->Get(object_name, 0, &dv, nullptr, nullptr);
SysFreeString(object_name);
- if (hr == S_OK) {
+ if (hr == S_OK && dv.vt == VT_BSTR) {
driver_version = String(V_BSTR(&dv));
+ } else {
+ driver_version = "Unknown";
}
for (ULONG i = 0; i < resultCount; i++) {
SAFE_RELEASE(pnpSDriverObject[i])
| diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp
index e5737df2ae5f..b54a821cd809 100644
--- a/platform/windows/os_windows.cpp
+++ b/platform/windows/os_windows.cpp
@@ -723,7 +723,7 @@ Vector<String> OS_Windows::get_video_adapter_driver_info() const {
BSTR object_name = SysAllocString(L"DriverName");
hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
+ if (hr == S_OK && dn.vt == VT_BSTR) {
String d_name = String(V_BSTR(&dn));
if (d_name.is_empty()) {
object_name = SysAllocString(L"DriverProviderName");
@@ -739,8 +739,10 @@ Vector<String> OS_Windows::get_video_adapter_driver_info() const {
object_name = SysAllocString(L"DriverProviderName");
hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
SysFreeString(object_name);
- if (hr == S_OK) {
+ if (hr == S_OK && dn.vt == VT_BSTR) {
driver_name = String(V_BSTR(&dn));
+ } else {
+ driver_name = "Unknown";
}
@@ -749,8 +751,10 @@ Vector<String> OS_Windows::get_video_adapter_driver_info() const {
object_name = SysAllocString(L"DriverVersion");
hr = pnpSDriverObject[0]->Get(object_name, 0, &dv, nullptr, nullptr);
+ if (hr == S_OK && dv.vt == VT_BSTR) {
driver_version = String(V_BSTR(&dv));
+ } else {
+ driver_version = "Unknown";
for (ULONG i = 0; i < resultCount; i++) {
SAFE_RELEASE(pnpSDriverObject[i]) | [] | [] | {
"additions": 7,
"author": "jss2a98aj",
"deletions": 3,
"html_url": "https://github.com/godotengine/godot/pull/105548",
"issue_id": 105548,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 105548,
"repo": "godotengine/godot",
"title": "Ensure `VARIANT` instances are actually `VT_BSTR` before treating them as such in `OS_Windows::get_video_adapter_driver_info()`",
"total_changes": 10
} |
723 | diff --git a/platform/android/SCsub b/platform/android/SCsub
index 72d36eabfc6f..ca0747b5368c 100644
--- a/platform/android/SCsub
+++ b/platform/android/SCsub
@@ -86,7 +86,7 @@ if lib_arch_dir != "":
)
env_android.CommandNoCache(out_dir + "/libc++_shared.so", stl_lib_path, Copy("$TARGET", "$SOURCE"))
- def generate_apk(target, source, env):
+ def generate_android_binaries(target, source, env):
gradle_process = []
if sys.platform.startswith("win"):
@@ -103,7 +103,7 @@ if lib_arch_dir != "":
"--quiet",
]
- if env["debug_symbols"]:
+ if env["gradle_do_not_strip"]:
gradle_process += ["-PdoNotStrip=true"]
subprocess.run(
@@ -111,5 +111,7 @@ if lib_arch_dir != "":
cwd="platform/android/java",
)
- if env["generate_apk"]:
- env_android.AlwaysBuild(env_android.CommandNoCache("generate_apk", lib, env.Run(generate_apk)))
+ if env["generate_android_binaries"]:
+ env_android.AlwaysBuild(
+ env_android.CommandNoCache("generate_android_binaries", lib, env.Run(generate_android_binaries))
+ )
diff --git a/platform/android/detect.py b/platform/android/detect.py
index cac7c3f48d4e..4e600f6f7fe7 100644
--- a/platform/android/detect.py
+++ b/platform/android/detect.py
@@ -34,8 +34,13 @@ def get_opts():
"android-" + str(get_min_target_api()),
),
BoolVariable("store_release", "Editor build for Google Play Store (for official builds only)", False),
- BoolVariable("generate_apk", "Generate an APK/AAB after building Android library by calling Gradle", False),
+ BoolVariable(
+ "generate_android_binaries",
+ "Generate APK, AAB & AAR binaries after building Android library by calling Gradle",
+ False,
+ ),
BoolVariable("swappy", "Use Swappy Frame Pacing library", False),
+ BoolVariable("gradle_do_not_strip", "Whether Gradle should strip the Android *.so libraries or not", False),
]
diff --git a/platform/android/java/app/build.gradle b/platform/android/java/app/build.gradle
index a3d1a715a953..4db13908ef8c 100644
--- a/platform/android/java/app/build.gradle
+++ b/platform/android/java/app/build.gradle
@@ -101,6 +101,7 @@ android {
}
ndk {
+ debugSymbolLevel 'FULL'
String[] export_abi_list = getExportEnabledABIs()
abiFilters export_abi_list
}
diff --git a/platform/android/java/build.gradle b/platform/android/java/build.gradle
index bbdf03612c3b..94433c7ab5d9 100644
--- a/platform/android/java/build.gradle
+++ b/platform/android/java/build.gradle
@@ -173,9 +173,14 @@ def generateBuildTasks(String flavor = "template", String edition = "standard",
buildTasks += tasks.create(name: copyBinaryTaskName, type: Copy) {
String filenameSuffix = edition == "mono" ? "${edition}${capitalizedTarget}" : target
dependsOn ":app:assemble${capitalizedEdition}${capitalizedTarget}"
- from("app/build/outputs/apk/${edition}/${target}")
+ from("app/build/outputs/apk/${edition}/${target}") {
+ include("android_${filenameSuffix}.apk")
+ }
+ from("app/build/outputs/native-debug-symbols/${edition}${capitalizedTarget}") {
+ include("native-debug-symbols.zip")
+ rename ("native-debug-symbols.zip", "android-template-${edition}-${target}-native-debug-symbols.zip")
+ }
into(binDir)
- include("android_${filenameSuffix}.apk")
}
}
} else {
@@ -186,9 +191,14 @@ def generateBuildTasks(String flavor = "template", String edition = "standard",
} else {
buildTasks += tasks.create(name: copyEditorApkTaskName, type: Copy) {
dependsOn ":editor:assemble${capitalizedAndroidDistro}${capitalizedTarget}"
- from("editor/build/outputs/apk/${androidDistro}/${target}")
+ from("editor/build/outputs/apk/${androidDistro}/${target}") {
+ include("android_editor-${androidDistro}-${target}*.apk")
+ }
+ from("editor/build/outputs/native-debug-symbols/${androidDistro}${capitalizedTarget}") {
+ include("native-debug-symbols.zip")
+ rename ("native-debug-symbols.zip", "android-editor-${androidDistro}-${target}-native-debug-symbols.zip")
+ }
into(androidEditorBuildsDir)
- include("android_editor-${androidDistro}-${target}*.apk")
}
}
@@ -270,19 +280,6 @@ task generateGodotMonoTemplates {
finalizedBy 'zipGradleBuild'
}
-/**
- * Generates the same output as generateGodotTemplates but with dev symbols
- */
-task generateDevTemplate {
- // add parameter to set symbols to true
- project.ext.doNotStrip = "true"
-
- gradle.startParameter.excludedTaskNames += templateExcludedBuildTask()
- dependsOn = generateBuildTasks("template")
-
- finalizedBy 'zipGradleBuild'
-}
-
task clean(type: Delete) {
dependsOn 'cleanGodotEditor'
dependsOn 'cleanGodotTemplates'
@@ -326,11 +323,17 @@ task cleanGodotTemplates(type: Delete) {
// Delete the Godot templates in the Godot bin directory
delete("$binDir/android_debug.apk")
+ delete("$binDir/android-template-standard-debug-native-debug-symbols.zip")
delete("$binDir/android_dev.apk")
+ delete("$binDir/android-template-standard-dev-native-debug-symbols.zip")
delete("$binDir/android_release.apk")
+ delete("$binDir/android-template-standard-release-native-debug-symbols.zip")
delete("$binDir/android_monoDebug.apk")
+ delete("$binDir/android-template-mono-debug-native-debug-symbols.zip")
delete("$binDir/android_monoDev.apk")
+ delete("$binDir/android-template-mono-dev-native-debug-symbols.zip")
delete("$binDir/android_monoRelease.apk")
+ delete("$binDir/android-template-mono-release-native-debug-symbols.zip")
delete("$binDir/android_source.zip")
delete("$binDir/godot-lib.template_debug.aar")
delete("$binDir/godot-lib.template_debug.dev.aar")
diff --git a/platform/android/java/editor/build.gradle b/platform/android/java/editor/build.gradle
index bfc123c8cd8a..86eb2bd585d5 100644
--- a/platform/android/java/editor/build.gradle
+++ b/platform/android/java/editor/build.gradle
@@ -89,6 +89,8 @@ android {
editorAppName: "Godot Engine 4",
editorBuildSuffix: ""
]
+
+ ndk { debugSymbolLevel 'FULL' }
}
base {
| diff --git a/platform/android/SCsub b/platform/android/SCsub
index 72d36eabfc6f..ca0747b5368c 100644
--- a/platform/android/SCsub
+++ b/platform/android/SCsub
@@ -86,7 +86,7 @@ if lib_arch_dir != "":
)
env_android.CommandNoCache(out_dir + "/libc++_shared.so", stl_lib_path, Copy("$TARGET", "$SOURCE"))
- def generate_apk(target, source, env):
+ def generate_android_binaries(target, source, env):
gradle_process = []
if sys.platform.startswith("win"):
@@ -103,7 +103,7 @@ if lib_arch_dir != "":
"--quiet",
- if env["debug_symbols"]:
+ if env["gradle_do_not_strip"]:
gradle_process += ["-PdoNotStrip=true"]
subprocess.run(
@@ -111,5 +111,7 @@ if lib_arch_dir != "":
cwd="platform/android/java",
)
- if env["generate_apk"]:
+ if env["generate_android_binaries"]:
+ env_android.AlwaysBuild(
+ env_android.CommandNoCache("generate_android_binaries", lib, env.Run(generate_android_binaries))
+ )
diff --git a/platform/android/detect.py b/platform/android/detect.py
index cac7c3f48d4e..4e600f6f7fe7 100644
--- a/platform/android/detect.py
+++ b/platform/android/detect.py
@@ -34,8 +34,13 @@ def get_opts():
"android-" + str(get_min_target_api()),
),
BoolVariable("store_release", "Editor build for Google Play Store (for official builds only)", False),
- BoolVariable("generate_apk", "Generate an APK/AAB after building Android library by calling Gradle", False),
+ BoolVariable(
+ "generate_android_binaries",
+ "Generate APK, AAB & AAR binaries after building Android library by calling Gradle",
+ False,
+ ),
BoolVariable("swappy", "Use Swappy Frame Pacing library", False),
+ BoolVariable("gradle_do_not_strip", "Whether Gradle should strip the Android *.so libraries or not", False),
]
diff --git a/platform/android/java/app/build.gradle b/platform/android/java/app/build.gradle
index a3d1a715a953..4db13908ef8c 100644
--- a/platform/android/java/app/build.gradle
+++ b/platform/android/java/app/build.gradle
@@ -101,6 +101,7 @@ android {
ndk {
+ debugSymbolLevel 'FULL'
String[] export_abi_list = getExportEnabledABIs()
abiFilters export_abi_list
diff --git a/platform/android/java/build.gradle b/platform/android/java/build.gradle
index bbdf03612c3b..94433c7ab5d9 100644
--- a/platform/android/java/build.gradle
+++ b/platform/android/java/build.gradle
@@ -173,9 +173,14 @@ def generateBuildTasks(String flavor = "template", String edition = "standard",
buildTasks += tasks.create(name: copyBinaryTaskName, type: Copy) {
String filenameSuffix = edition == "mono" ? "${edition}${capitalizedTarget}" : target
dependsOn ":app:assemble${capitalizedEdition}${capitalizedTarget}"
- from("app/build/outputs/apk/${edition}/${target}")
+ from("app/build/outputs/apk/${edition}/${target}") {
+ include("android_${filenameSuffix}.apk")
+ from("app/build/outputs/native-debug-symbols/${edition}${capitalizedTarget}") {
+ rename ("native-debug-symbols.zip", "android-template-${edition}-${target}-native-debug-symbols.zip")
into(binDir)
- include("android_${filenameSuffix}.apk")
} else {
@@ -186,9 +191,14 @@ def generateBuildTasks(String flavor = "template", String edition = "standard",
} else {
buildTasks += tasks.create(name: copyEditorApkTaskName, type: Copy) {
dependsOn ":editor:assemble${capitalizedAndroidDistro}${capitalizedTarget}"
- from("editor/build/outputs/apk/${androidDistro}/${target}")
+ from("editor/build/outputs/apk/${androidDistro}/${target}") {
+ include("android_editor-${androidDistro}-${target}*.apk")
+ rename ("native-debug-symbols.zip", "android-editor-${androidDistro}-${target}-native-debug-symbols.zip")
into(androidEditorBuildsDir)
- include("android_editor-${androidDistro}-${target}*.apk")
@@ -270,19 +280,6 @@ task generateGodotMonoTemplates {
finalizedBy 'zipGradleBuild'
}
-/**
- * Generates the same output as generateGodotTemplates but with dev symbols
- */
- // add parameter to set symbols to true
- project.ext.doNotStrip = "true"
- gradle.startParameter.excludedTaskNames += templateExcludedBuildTask()
- dependsOn = generateBuildTasks("template")
- finalizedBy 'zipGradleBuild'
-}
task clean(type: Delete) {
dependsOn 'cleanGodotEditor'
dependsOn 'cleanGodotTemplates'
@@ -326,11 +323,17 @@ task cleanGodotTemplates(type: Delete) {
// Delete the Godot templates in the Godot bin directory
delete("$binDir/android_debug.apk")
+ delete("$binDir/android-template-standard-debug-native-debug-symbols.zip")
delete("$binDir/android_dev.apk")
+ delete("$binDir/android-template-standard-dev-native-debug-symbols.zip")
delete("$binDir/android_release.apk")
+ delete("$binDir/android-template-standard-release-native-debug-symbols.zip")
delete("$binDir/android_monoDebug.apk")
+ delete("$binDir/android-template-mono-debug-native-debug-symbols.zip")
delete("$binDir/android_monoDev.apk")
+ delete("$binDir/android-template-mono-dev-native-debug-symbols.zip")
delete("$binDir/android_monoRelease.apk")
+ delete("$binDir/android-template-mono-release-native-debug-symbols.zip")
delete("$binDir/android_source.zip")
delete("$binDir/godot-lib.template_debug.aar")
delete("$binDir/godot-lib.template_debug.dev.aar")
diff --git a/platform/android/java/editor/build.gradle b/platform/android/java/editor/build.gradle
index bfc123c8cd8a..86eb2bd585d5 100644
--- a/platform/android/java/editor/build.gradle
+++ b/platform/android/java/editor/build.gradle
@@ -89,6 +89,8 @@ android {
editorAppName: "Godot Engine 4",
editorBuildSuffix: ""
+
+ ndk { debugSymbolLevel 'FULL' }
}
base { | [
"- env_android.AlwaysBuild(env_android.CommandNoCache(\"generate_apk\", lib, env.Run(generate_apk)))",
"+ from(\"editor/build/outputs/native-debug-symbols/${androidDistro}${capitalizedTarget}\") {",
"-task generateDevTemplate {"
] | [
27,
92,
108
] | {
"additions": 35,
"author": "m4gr3d",
"deletions": 22,
"html_url": "https://github.com/godotengine/godot/pull/105605",
"issue_id": 105605,
"merged_at": "2025-04-22T23:28:42Z",
"omission_probability": 0.1,
"pr_number": 105605,
"repo": "godotengine/godot",
"title": "Android: Enable native debug symbols generation",
"total_changes": 57
} |
724 | diff --git a/core/variant/array.cpp b/core/variant/array.cpp
index 81caa5d14741..b82af8682ae9 100644
--- a/core/variant/array.cpp
+++ b/core/variant/array.cpp
@@ -801,47 +801,45 @@ Variant Array::pop_at(int p_pos) {
}
Variant Array::min() const {
- Variant minval;
- for (int i = 0; i < size(); i++) {
- if (i == 0) {
- minval = get(i);
- } else {
- bool valid;
- Variant ret;
- Variant test = get(i);
- Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
- if (!valid) {
- return Variant(); //not a valid comparison
- }
- if (bool(ret)) {
- //is less
- minval = test;
- }
+ int array_size = size();
+ if (array_size == 0) {
+ return Variant();
+ }
+
+ int min_index = 0;
+ Variant is_less;
+ for (int i = 1; i < array_size; i++) {
+ bool valid;
+ Variant::evaluate(Variant::OP_LESS, _p->array[i], _p->array[min_index], is_less, valid);
+ if (!valid) {
+ return Variant(); //not a valid comparison
+ }
+ if (bool(is_less)) {
+ min_index = i;
}
}
- return minval;
+ return _p->array[min_index];
}
Variant Array::max() const {
- Variant maxval;
- for (int i = 0; i < size(); i++) {
- if (i == 0) {
- maxval = get(i);
- } else {
- bool valid;
- Variant ret;
- Variant test = get(i);
- Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
- if (!valid) {
- return Variant(); //not a valid comparison
- }
- if (bool(ret)) {
- //is greater
- maxval = test;
- }
+ int array_size = size();
+ if (array_size == 0) {
+ return Variant();
+ }
+
+ int max_index = 0;
+ Variant is_greater;
+ for (int i = 1; i < array_size; i++) {
+ bool valid;
+ Variant::evaluate(Variant::OP_GREATER, _p->array[i], _p->array[max_index], is_greater, valid);
+ if (!valid) {
+ return Variant(); //not a valid comparison
+ }
+ if (bool(is_greater)) {
+ max_index = i;
}
}
- return maxval;
+ return _p->array[max_index];
}
const void *Array::id() const {
| diff --git a/core/variant/array.cpp b/core/variant/array.cpp
index 81caa5d14741..b82af8682ae9 100644
--- a/core/variant/array.cpp
+++ b/core/variant/array.cpp
@@ -801,47 +801,45 @@ Variant Array::pop_at(int p_pos) {
Variant Array::min() const {
- Variant minval;
- minval = get(i);
- Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
- //is less
+ int min_index = 0;
+ Variant is_less;
+ Variant::evaluate(Variant::OP_LESS, _p->array[i], _p->array[min_index], is_less, valid);
+ if (bool(is_less)) {
+ min_index = i;
- return minval;
+ return _p->array[min_index];
Variant Array::max() const {
- Variant maxval;
- maxval = get(i);
- Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
- //is greater
- maxval = test;
+ int max_index = 0;
+ Variant is_greater;
+ Variant::evaluate(Variant::OP_GREATER, _p->array[i], _p->array[max_index], is_greater, valid);
+ if (bool(is_greater)) {
+ max_index = i;
- return maxval;
+ return _p->array[max_index];
const void *Array::id() const { | [
"-\t\t\t\tminval = test;"
] | [
22
] | {
"additions": 32,
"author": "aaronp64",
"deletions": 34,
"html_url": "https://github.com/godotengine/godot/pull/105392",
"issue_id": 105392,
"merged_at": "2025-04-15T17:33:20Z",
"omission_probability": 0.1,
"pr_number": 105392,
"repo": "godotengine/godot",
"title": "Optimize `Array` `min`/`max` methods",
"total_changes": 66
} |
725 | diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp
index e4cc0f9c03b1..07e00b099a8e 100644
--- a/core/config/project_settings.cpp
+++ b/core/config/project_settings.cpp
@@ -1612,6 +1612,7 @@ ProjectSettings::ProjectSettings() {
GLOBAL_DEF_BASIC("input_devices/pointing/android/enable_long_press_as_right_click", false);
GLOBAL_DEF_BASIC("input_devices/pointing/android/enable_pan_and_scale_gestures", false);
GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "input_devices/pointing/android/rotary_input_scroll_axis", PROPERTY_HINT_ENUM, "Horizontal,Vertical"), 1);
+ GLOBAL_DEF("input_devices/pointing/android/override_volume_buttons", false);
// These properties will not show up in the dialog. If you want to exclude whole groups, use add_hidden_prefix().
GLOBAL_DEF_INTERNAL("application/config/features", PackedStringArray());
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index 1a29e2003e94..f182d873aa22 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -1444,6 +1444,9 @@
<member name="input_devices/pointing/android/enable_pan_and_scale_gestures" type="bool" setter="" getter="" default="false">
If [code]true[/code], multi-touch pan and scale gestures are enabled on Android devices.
</member>
+ <member name="input_devices/pointing/android/override_volume_buttons" type="bool" setter="" getter="" default="false">
+ If [code]true[/code], system volume changes are disabled when the buttons are used within the app.
+ </member>
<member name="input_devices/pointing/android/rotary_input_scroll_axis" type="int" setter="" getter="" default="1">
On Wear OS devices, defines which axis of the mouse wheel rotary input is mapped to. This rotary input is usually performed by rotating the physical or virtual (touch-based) bezel on a smartwatch.
</member>
diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt
index 4a7612c28fa4..c9f717ec810c 100644
--- a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt
+++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt
@@ -258,12 +258,14 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListe
super.onGodotSetupCompleted()
val longPressEnabled = enableLongPressGestures()
val panScaleEnabled = enablePanAndScaleGestures()
+ val overrideVolumeButtonsEnabled = overrideVolumeButtons()
runOnUiThread {
// Enable long press, panning and scaling gestures
godotFragment?.godot?.renderView?.inputHandler?.apply {
enableLongPress(longPressEnabled)
enablePanningAndScalingGestures(panScaleEnabled)
+ setOverrideVolumeButtons(overrideVolumeButtonsEnabled)
}
}
}
@@ -482,6 +484,8 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListe
*/
protected open fun overrideOrientationRequest() = true
+ protected open fun overrideVolumeButtons() = false
+
/**
* Enable long press gestures for the Godot Android editor.
*/
diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotGame.kt b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotGame.kt
index ed1ecb855cc5..7290f7462715 100644
--- a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotGame.kt
+++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotGame.kt
@@ -46,6 +46,8 @@ abstract class BaseGodotGame: GodotEditor() {
private val TAG = BaseGodotGame::class.java.simpleName
}
+ override fun overrideVolumeButtons() = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/override_volume_buttons"))
+
override fun enableLongPressGestures() = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/enable_long_press_as_right_click"))
override fun enablePanAndScaleGestures() = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/enable_pan_and_scale_gestures"))
diff --git a/platform/android/java/lib/src/org/godotengine/godot/Godot.kt b/platform/android/java/lib/src/org/godotengine/godot/Godot.kt
index 550fbe94de71..9ab30e5f5b66 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/Godot.kt
+++ b/platform/android/java/lib/src/org/godotengine/godot/Godot.kt
@@ -714,11 +714,13 @@ class Godot(private val context: Context) {
val longPressEnabled = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/enable_long_press_as_right_click"))
val panScaleEnabled = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/enable_pan_and_scale_gestures"))
val rotaryInputAxisValue = GodotLib.getGlobal("input_devices/pointing/android/rotary_input_scroll_axis")
+ val overrideVolumeButtons = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/override_volume_buttons"))
runOnUiThread {
renderView?.inputHandler?.apply {
enableLongPress(longPressEnabled)
enablePanningAndScalingGestures(panScaleEnabled)
+ setOverrideVolumeButtons(overrideVolumeButtons)
try {
setRotaryInputAxis(Integer.parseInt(rotaryInputAxisValue))
} catch (e: NumberFormatException) {
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
index 6f036c15a32a..da3ad6e831cb 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
@@ -88,6 +88,7 @@ public class GodotInputHandler implements InputManager.InputDeviceListener, Sens
private int rotaryInputAxis = ROTARY_INPUT_VERTICAL_AXIS;
private int cachedRotation = -1;
+ private boolean overrideVolumeButtons = false;
public GodotInputHandler(Context context, Godot godot) {
this.godot = godot;
@@ -136,6 +137,10 @@ public void setRotaryInputAxis(int axis) {
rotaryInputAxis = axis;
}
+ public void setOverrideVolumeButtons(boolean value) {
+ overrideVolumeButtons = value;
+ }
+
boolean hasHardwareKeyboard() {
return !mHardwareKeyboardIds.isEmpty();
}
@@ -157,10 +162,6 @@ public void onPointerCaptureChange(boolean hasCapture) {
}
public boolean onKeyUp(final int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
- return false;
- }
-
int source = event.getSource();
if (isKeyEventGameDevice(source)) {
// Check if the device exists
@@ -178,14 +179,14 @@ public boolean onKeyUp(final int keyCode, KeyEvent event) {
handleKeyEvent(physical_keycode, unicode, key_label, false, event.getRepeatCount() > 0);
};
+ if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
+ return overrideVolumeButtons;
+ }
+
return true;
}
public boolean onKeyDown(final int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
- return false;
- }
-
int source = event.getSource();
final int deviceId = event.getDeviceId();
@@ -206,6 +207,10 @@ public boolean onKeyDown(final int keyCode, KeyEvent event) {
handleKeyEvent(physical_keycode, unicode, key_label, true, event.getRepeatCount() > 0);
}
+ if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
+ return overrideVolumeButtons;
+ }
+
return true;
}
| diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp
index e4cc0f9c03b1..07e00b099a8e 100644
--- a/core/config/project_settings.cpp
+++ b/core/config/project_settings.cpp
@@ -1612,6 +1612,7 @@ ProjectSettings::ProjectSettings() {
GLOBAL_DEF_BASIC("input_devices/pointing/android/enable_long_press_as_right_click", false);
GLOBAL_DEF_BASIC("input_devices/pointing/android/enable_pan_and_scale_gestures", false);
GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "input_devices/pointing/android/rotary_input_scroll_axis", PROPERTY_HINT_ENUM, "Horizontal,Vertical"), 1);
+ GLOBAL_DEF("input_devices/pointing/android/override_volume_buttons", false);
// These properties will not show up in the dialog. If you want to exclude whole groups, use add_hidden_prefix().
GLOBAL_DEF_INTERNAL("application/config/features", PackedStringArray());
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index 1a29e2003e94..f182d873aa22 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -1444,6 +1444,9 @@
<member name="input_devices/pointing/android/enable_pan_and_scale_gestures" type="bool" setter="" getter="" default="false">
If [code]true[/code], multi-touch pan and scale gestures are enabled on Android devices.
+ <member name="input_devices/pointing/android/override_volume_buttons" type="bool" setter="" getter="" default="false">
+ If [code]true[/code], system volume changes are disabled when the buttons are used within the app.
+ </member>
<member name="input_devices/pointing/android/rotary_input_scroll_axis" type="int" setter="" getter="" default="1">
On Wear OS devices, defines which axis of the mouse wheel rotary input is mapped to. This rotary input is usually performed by rotating the physical or virtual (touch-based) bezel on a smartwatch.
diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt
index 4a7612c28fa4..c9f717ec810c 100644
--- a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt
+++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt
@@ -258,12 +258,14 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListe
super.onGodotSetupCompleted()
val longPressEnabled = enableLongPressGestures()
val panScaleEnabled = enablePanAndScaleGestures()
// Enable long press, panning and scaling gestures
godotFragment?.godot?.renderView?.inputHandler?.apply {
+ setOverrideVolumeButtons(overrideVolumeButtonsEnabled)
}
@@ -482,6 +484,8 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListe
protected open fun overrideOrientationRequest() = true
+ protected open fun overrideVolumeButtons() = false
/**
* Enable long press gestures for the Godot Android editor.
diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotGame.kt b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotGame.kt
index ed1ecb855cc5..7290f7462715 100644
--- a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotGame.kt
+++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotGame.kt
@@ -46,6 +46,8 @@ abstract class BaseGodotGame: GodotEditor() {
private val TAG = BaseGodotGame::class.java.simpleName
+ override fun overrideVolumeButtons() = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/override_volume_buttons"))
override fun enableLongPressGestures() = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/enable_long_press_as_right_click"))
override fun enablePanAndScaleGestures() = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/enable_pan_and_scale_gestures"))
diff --git a/platform/android/java/lib/src/org/godotengine/godot/Godot.kt b/platform/android/java/lib/src/org/godotengine/godot/Godot.kt
index 550fbe94de71..9ab30e5f5b66 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/Godot.kt
+++ b/platform/android/java/lib/src/org/godotengine/godot/Godot.kt
@@ -714,11 +714,13 @@ class Godot(private val context: Context) {
val longPressEnabled = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/enable_long_press_as_right_click"))
val panScaleEnabled = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/enable_pan_and_scale_gestures"))
val rotaryInputAxisValue = GodotLib.getGlobal("input_devices/pointing/android/rotary_input_scroll_axis")
+ val overrideVolumeButtons = java.lang.Boolean.parseBoolean(GodotLib.getGlobal("input_devices/pointing/android/override_volume_buttons"))
renderView?.inputHandler?.apply {
+ setOverrideVolumeButtons(overrideVolumeButtons)
try {
setRotaryInputAxis(Integer.parseInt(rotaryInputAxisValue))
} catch (e: NumberFormatException) {
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
index 6f036c15a32a..da3ad6e831cb 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
@@ -88,6 +88,7 @@ public class GodotInputHandler implements InputManager.InputDeviceListener, Sens
private int rotaryInputAxis = ROTARY_INPUT_VERTICAL_AXIS;
private int cachedRotation = -1;
+ private boolean overrideVolumeButtons = false;
public GodotInputHandler(Context context, Godot godot) {
this.godot = godot;
@@ -136,6 +137,10 @@ public void setRotaryInputAxis(int axis) {
rotaryInputAxis = axis;
+ public void setOverrideVolumeButtons(boolean value) {
+ overrideVolumeButtons = value;
+ }
boolean hasHardwareKeyboard() {
return !mHardwareKeyboardIds.isEmpty();
@@ -157,10 +162,6 @@ public void onPointerCaptureChange(boolean hasCapture) {
public boolean onKeyUp(final int keyCode, KeyEvent event) {
if (isKeyEventGameDevice(source)) {
// Check if the device exists
@@ -178,14 +179,14 @@ public boolean onKeyUp(final int keyCode, KeyEvent event) {
handleKeyEvent(physical_keycode, unicode, key_label, false, event.getRepeatCount() > 0);
};
public boolean onKeyDown(final int keyCode, KeyEvent event) {
final int deviceId = event.getDeviceId();
@@ -206,6 +207,10 @@ public boolean onKeyDown(final int keyCode, KeyEvent event) {
handleKeyEvent(physical_keycode, unicode, key_label, true, event.getRepeatCount() > 0); | [
"+\t\tval overrideVolumeButtonsEnabled = overrideVolumeButtons()"
] | [
34
] | {
"additions": 25,
"author": "syntaxerror247",
"deletions": 8,
"html_url": "https://github.com/godotengine/godot/pull/102984",
"issue_id": 102984,
"merged_at": "2025-03-11T14:42:27Z",
"omission_probability": 0.1,
"pr_number": 102984,
"repo": "godotengine/godot",
"title": "Android: enable support for volume button events",
"total_changes": 33
} |
726 | diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp
index 546dae618387..e52fa217701c 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp
@@ -551,6 +551,9 @@ void GridMapEditor::_fill_selection() {
void GridMapEditor::_clear_clipboard_data() {
for (const ClipboardItem &E : clipboard_items) {
+ if (E.instance.is_null()) {
+ continue;
+ }
RenderingServer::get_singleton()->free(E.instance);
}
@@ -581,6 +584,10 @@ void GridMapEditor::_set_clipboard_data() {
item.orientation = node->get_cell_item_orientation(selected);
item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), scenario);
+ if (mesh.is_valid()) {
+ item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), scenario);
+ }
+
clipboard_items.push_back(item);
}
}
@@ -608,6 +615,9 @@ void GridMapEditor::_update_paste_indicator() {
RenderingServer::get_singleton()->instance_set_transform(paste_instance, node->get_global_transform() * xf);
for (const ClipboardItem &item : clipboard_items) {
+ if (item.instance.is_null()) {
+ continue;
+ }
xf = Transform3D();
xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size();
xf.basis = rot * xf.basis;
| diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp
index 546dae618387..e52fa217701c 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp
@@ -551,6 +551,9 @@ void GridMapEditor::_fill_selection() {
void GridMapEditor::_clear_clipboard_data() {
for (const ClipboardItem &E : clipboard_items) {
+ if (E.instance.is_null()) {
RenderingServer::get_singleton()->free(E.instance);
}
@@ -581,6 +584,10 @@ void GridMapEditor::_set_clipboard_data() {
item.orientation = node->get_cell_item_orientation(selected);
item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), scenario);
+ item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), scenario);
+ }
+
clipboard_items.push_back(item);
}
}
@@ -608,6 +615,9 @@ void GridMapEditor::_update_paste_indicator() {
RenderingServer::get_singleton()->instance_set_transform(paste_instance, node->get_global_transform() * xf);
for (const ClipboardItem &item : clipboard_items) {
+ if (item.instance.is_null()) {
xf = Transform3D();
xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size();
xf.basis = rot * xf.basis; | [
"+\t\t\t\tif (mesh.is_valid()) {"
] | [
18
] | {
"additions": 10,
"author": "smix8",
"deletions": 0,
"html_url": "https://github.com/godotengine/godot/pull/105664",
"issue_id": 105664,
"merged_at": "2025-04-22T23:28:42Z",
"omission_probability": 0.1,
"pr_number": 105664,
"repo": "godotengine/godot",
"title": "Fix GridMap move selection crashing on invalid MeshLibrary item",
"total_changes": 10
} |
727 | diff --git a/misc/msvs/nmake.substitution.props b/misc/msvs/nmake.substitution.props
index 05a155eb9ebc..3f94fc4c1e7e 100644
--- a/misc/msvs/nmake.substitution.props
+++ b/misc/msvs/nmake.substitution.props
@@ -16,4 +16,23 @@
<Target Name="Clean">
<Exec Command="$(NMakeCleanCommandLine)"/>
</Target>
+ <ItemDefinitionGroup>
+ <ClCompile>
+ <AdditionalOptions>$(AdditionalOptions)</AdditionalOptions>
+ <ForcedIncludeFiles>$(NMakeForcedIncludes)</ForcedIncludeFiles>
+ <ForcedUsingFiles>$(NMakeForcedUsingAssemblies)</ForcedUsingFiles>
+ <PreprocessorDefinitions>$(NMakePreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <!-- check get_platforms in each msvs.py for possible value of those conditions -->
+ <!-- MSVC Platform.Common.props for possible TargetMachine values -->
+ <Link Condition="'$(Platform)' == 'arm64'">
+ <TargetMachine>MachineARM64</TargetMachine>
+ </Link>
+ <Link Condition="'$(Platform)' == 'x64'">
+ <TargetMachine>MachineX64</TargetMachine>
+ </Link>
+ <Link Condition="'$(Platform)' == 'Win32'">
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
</Project>
| diff --git a/misc/msvs/nmake.substitution.props b/misc/msvs/nmake.substitution.props
index 05a155eb9ebc..3f94fc4c1e7e 100644
--- a/misc/msvs/nmake.substitution.props
+++ b/misc/msvs/nmake.substitution.props
@@ -16,4 +16,23 @@
<Target Name="Clean">
<Exec Command="$(NMakeCleanCommandLine)"/>
</Target>
+ <ItemDefinitionGroup>
+ <ClCompile>
+ <AdditionalOptions>$(AdditionalOptions)</AdditionalOptions>
+ <ForcedIncludeFiles>$(NMakeForcedIncludes)</ForcedIncludeFiles>
+ <ForcedUsingFiles>$(NMakeForcedUsingAssemblies)</ForcedUsingFiles>
+ <PreprocessorDefinitions>$(NMakePreprocessorDefinitions)</PreprocessorDefinitions>
+ <!-- check get_platforms in each msvs.py for possible value of those conditions -->
+ <!-- MSVC Platform.Common.props for possible TargetMachine values -->
+ <Link Condition="'$(Platform)' == 'arm64'">
+ <TargetMachine>MachineARM64</TargetMachine>
+ <Link Condition="'$(Platform)' == 'x64'">
+ <TargetMachine>MachineX64</TargetMachine>
+ <Link Condition="'$(Platform)' == 'Win32'">
+ <TargetMachine>MachineX86</TargetMachine>
+ </ItemDefinitionGroup>
</Project> | [
"+ </ClCompile>"
] | [
14
] | {
"additions": 19,
"author": "van800",
"deletions": 0,
"html_url": "https://github.com/godotengine/godot/pull/105650",
"issue_id": 105650,
"merged_at": "2025-04-22T23:28:42Z",
"omission_probability": 0.1,
"pr_number": 105650,
"repo": "godotengine/godot",
"title": "Fixes for `.sln` project generation for Rider on Mac/Linux",
"total_changes": 19
} |
728 | diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp
index 4cde5a9646e6..4a5969727d95 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp
@@ -562,6 +562,8 @@ void GridMapEditor::_set_clipboard_data() {
Ref<MeshLibrary> meshLibrary = node->get_mesh_library();
+ const RID scenario = get_tree()->get_root()->get_world_3d()->get_scenario();
+
for (int i = selection.begin.x; i <= selection.end.x; i++) {
for (int j = selection.begin.y; j <= selection.end.y; j++) {
for (int k = selection.begin.z; k <= selection.end.z; k++) {
@@ -577,7 +579,7 @@ void GridMapEditor::_set_clipboard_data() {
item.cell_item = itm;
item.grid_offset = Vector3(selected) - selection.begin;
item.orientation = node->get_cell_item_orientation(selected);
- item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world_3d()->get_scenario());
+ item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), scenario);
clipboard_items.push_back(item);
}
@@ -1181,20 +1183,23 @@ void GridMapEditor::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
mesh_library_palette->connect(SceneStringName(item_selected), callable_mp(this, &GridMapEditor::_item_selected_cbk));
+
+ const RID scenario = get_tree()->get_root()->get_world_3d()->get_scenario();
+
for (int i = 0; i < 3; i++) {
grid[i] = RS::get_singleton()->mesh_create();
- grid_instance[i] = RS::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world_3d()->get_scenario());
+ grid_instance[i] = RS::get_singleton()->instance_create2(grid[i], scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(grid_instance[i], 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
- selection_level_instance[i] = RenderingServer::get_singleton()->instance_create2(selection_level_mesh[i], get_tree()->get_root()->get_world_3d()->get_scenario());
+ selection_level_instance[i] = RenderingServer::get_singleton()->instance_create2(selection_level_mesh[i], scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(selection_level_instance[i], 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
}
- cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(cursor_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
RenderingServer::get_singleton()->instance_set_visible(cursor_instance, false);
- selection_instance = RenderingServer::get_singleton()->instance_create2(selection_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ selection_instance = RenderingServer::get_singleton()->instance_create2(selection_mesh, scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(selection_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
- paste_instance = RenderingServer::get_singleton()->instance_create2(paste_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ paste_instance = RenderingServer::get_singleton()->instance_create2(paste_mesh, scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(paste_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
_update_selection_transform();
@@ -1271,11 +1276,13 @@ void GridMapEditor::_update_cursor_instance() {
}
cursor_instance = RID();
+ const RID scenario = get_tree()->get_root()->get_world_3d()->get_scenario();
+
if (mode_buttons_group->get_pressed_button() == paint_mode_button) {
if (selected_palette >= 0 && node && node->get_mesh_library().is_valid()) {
Ref<Mesh> mesh = node->get_mesh_library()->get_item_mesh(selected_palette);
if (mesh.is_valid() && mesh->get_rid().is_valid()) {
- cursor_instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world_3d()->get_scenario());
+ cursor_instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), scenario);
RS::ShadowCastingSetting cast_shadows = (RS::ShadowCastingSetting)node->get_mesh_library()->get_item_mesh_cast_shadow(selected_palette);
RS::get_singleton()->instance_geometry_set_cast_shadows_setting(cursor_instance, cast_shadows);
}
@@ -1283,15 +1290,15 @@ void GridMapEditor::_update_cursor_instance() {
} else if (mode_buttons_group->get_pressed_button() == select_mode_button) {
cursor_inner_mat->set_albedo(Color(default_color, 0.2));
cursor_outer_mat->set_albedo(Color(default_color, 0.8));
- cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, scenario);
} else if (mode_buttons_group->get_pressed_button() == erase_mode_button) {
cursor_inner_mat->set_albedo(Color(erase_color, 0.2));
cursor_outer_mat->set_albedo(Color(erase_color, 0.8));
- cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, scenario);
} else if (mode_buttons_group->get_pressed_button() == pick_mode_button) {
cursor_inner_mat->set_albedo(Color(pick_color, 0.2));
cursor_outer_mat->set_albedo(Color(pick_color, 0.8));
- cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, scenario);
}
// Make the cursor translucent so that it can be distinguished from already-placed tiles.
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index ff52a67dbc7c..7d318e167c77 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -82,6 +82,8 @@ bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
Array meshes = p_value;
+ const RID scenario = get_world_3d()->get_scenario();
+
for (int i = 0; i < meshes.size(); i++) {
BakedMesh bm;
bm.mesh = meshes[i];
@@ -90,7 +92,7 @@ bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
RS::get_singleton()->instance_set_base(bm.instance, bm.mesh->get_rid());
RS::get_singleton()->instance_attach_object_instance_id(bm.instance, get_instance_id());
if (is_inside_tree()) {
- RS::get_singleton()->instance_set_scenario(bm.instance, get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_scenario(bm.instance, scenario);
RS::get_singleton()->instance_set_transform(bm.instance, get_global_transform());
}
baked_meshes.push_back(bm);
@@ -621,6 +623,18 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
HashMap<int, List<Pair<Transform3D, IndexKey>>> multimesh_items;
+ RID scenario;
+#ifndef NAVIGATION_3D_DISABLED
+ RID navigation_map;
+#endif
+
+ if (is_inside_tree()) {
+ scenario = get_world_3d()->get_scenario();
+#ifndef NAVIGATION_3D_DISABLED
+ navigation_map = get_world_3d()->get_navigation_map();
+#endif
+ }
+
for (const IndexKey &E : g.cells) {
ERR_CONTINUE(!cell_map.has(E));
const Cell &c = cell_map[E];
@@ -683,7 +697,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
if (map_override.is_valid()) {
NavigationServer3D::get_singleton()->region_set_map(region, map_override);
} else {
- NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map());
+ NavigationServer3D::get_singleton()->region_set_map(region, navigation_map);
}
}
nm.region = region;
@@ -698,7 +712,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
RS::get_singleton()->instance_set_base(nm.navigation_mesh_debug_instance, navigation_mesh_debug_rid);
}
if (is_inside_tree()) {
- RS::get_singleton()->instance_set_scenario(nm.navigation_mesh_debug_instance, get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_scenario(nm.navigation_mesh_debug_instance, scenario);
RS::get_singleton()->instance_set_transform(nm.navigation_mesh_debug_instance, get_global_transform() * nm.xform);
}
}
@@ -743,7 +757,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
RS::get_singleton()->instance_set_base(instance, mm);
if (is_inside_tree()) {
- RS::get_singleton()->instance_set_scenario(instance, get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_scenario(instance, scenario);
RS::get_singleton()->instance_set_transform(instance, get_global_transform());
}
@@ -802,22 +816,27 @@ void GridMap::_update_physics_bodies_characteristics() {
void GridMap::_octant_enter_world(const OctantKey &p_key) {
ERR_FAIL_COND(!octant_map.has(p_key));
Octant &g = *octant_map[p_key];
+
+ const RID scenario = get_world_3d()->get_scenario();
+
#ifndef PHYSICS_3D_DISABLED
PhysicsServer3D::get_singleton()->body_set_state(g.static_body, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
PhysicsServer3D::get_singleton()->body_set_space(g.static_body, get_world_3d()->get_space());
if (g.collision_debug_instance.is_valid()) {
- RS::get_singleton()->instance_set_scenario(g.collision_debug_instance, get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_scenario(g.collision_debug_instance, scenario);
RS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform());
}
#endif // PHYSICS_3D_DISABLED
for (int i = 0; i < g.multimesh_instances.size(); i++) {
- RS::get_singleton()->instance_set_scenario(g.multimesh_instances[i].instance, get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_scenario(g.multimesh_instances[i].instance, scenario);
RS::get_singleton()->instance_set_transform(g.multimesh_instances[i].instance, get_global_transform());
}
#ifndef NAVIGATION_3D_DISABLED
+ const RID navigation_map = get_world_3d()->get_navigation_map();
+
if (bake_navigation && mesh_library.is_valid()) {
for (KeyValue<IndexKey, Octant::NavigationCell> &F : g.navigation_cell_ids) {
if (cell_map.has(F.key) && F.value.region.is_valid() == false) {
@@ -831,7 +850,7 @@ void GridMap::_octant_enter_world(const OctantKey &p_key) {
if (map_override.is_valid()) {
NavigationServer3D::get_singleton()->region_set_map(region, map_override);
} else {
- NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map());
+ NavigationServer3D::get_singleton()->region_set_map(region, navigation_map);
}
F.value.region = region;
| diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp
index 4cde5a9646e6..4a5969727d95 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp
@@ -562,6 +562,8 @@ void GridMapEditor::_set_clipboard_data() {
Ref<MeshLibrary> meshLibrary = node->get_mesh_library();
for (int i = selection.begin.x; i <= selection.end.x; i++) {
for (int j = selection.begin.y; j <= selection.end.y; j++) {
for (int k = selection.begin.z; k <= selection.end.z; k++) {
@@ -577,7 +579,7 @@ void GridMapEditor::_set_clipboard_data() {
item.cell_item = itm;
item.grid_offset = Vector3(selected) - selection.begin;
item.orientation = node->get_cell_item_orientation(selected);
- item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world_3d()->get_scenario());
+ item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), scenario);
clipboard_items.push_back(item);
@@ -1181,20 +1183,23 @@ void GridMapEditor::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
mesh_library_palette->connect(SceneStringName(item_selected), callable_mp(this, &GridMapEditor::_item_selected_cbk));
+ const RID scenario = get_tree()->get_root()->get_world_3d()->get_scenario();
for (int i = 0; i < 3; i++) {
grid[i] = RS::get_singleton()->mesh_create();
- grid_instance[i] = RS::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world_3d()->get_scenario());
+ grid_instance[i] = RS::get_singleton()->instance_create2(grid[i], scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(grid_instance[i], 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
- selection_level_instance[i] = RenderingServer::get_singleton()->instance_create2(selection_level_mesh[i], get_tree()->get_root()->get_world_3d()->get_scenario());
+ selection_level_instance[i] = RenderingServer::get_singleton()->instance_create2(selection_level_mesh[i], scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(selection_level_instance[i], 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
+ cursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(cursor_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
RenderingServer::get_singleton()->instance_set_visible(cursor_instance, false);
- selection_instance = RenderingServer::get_singleton()->instance_create2(selection_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ selection_instance = RenderingServer::get_singleton()->instance_create2(selection_mesh, scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(selection_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
- paste_instance = RenderingServer::get_singleton()->instance_create2(paste_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ paste_instance = RenderingServer::get_singleton()->instance_create2(paste_mesh, scenario);
RenderingServer::get_singleton()->instance_set_layer_mask(paste_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
_update_selection_transform();
@@ -1271,11 +1276,13 @@ void GridMapEditor::_update_cursor_instance() {
cursor_instance = RID();
if (mode_buttons_group->get_pressed_button() == paint_mode_button) {
if (selected_palette >= 0 && node && node->get_mesh_library().is_valid()) {
Ref<Mesh> mesh = node->get_mesh_library()->get_item_mesh(selected_palette);
if (mesh.is_valid() && mesh->get_rid().is_valid()) {
- cursor_instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world_3d()->get_scenario());
+ cursor_instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), scenario);
RS::ShadowCastingSetting cast_shadows = (RS::ShadowCastingSetting)node->get_mesh_library()->get_item_mesh_cast_shadow(selected_palette);
RS::get_singleton()->instance_geometry_set_cast_shadows_setting(cursor_instance, cast_shadows);
@@ -1283,15 +1290,15 @@ void GridMapEditor::_update_cursor_instance() {
} else if (mode_buttons_group->get_pressed_button() == select_mode_button) {
cursor_inner_mat->set_albedo(Color(default_color, 0.2));
cursor_outer_mat->set_albedo(Color(default_color, 0.8));
} else if (mode_buttons_group->get_pressed_button() == erase_mode_button) {
cursor_inner_mat->set_albedo(Color(erase_color, 0.2));
cursor_outer_mat->set_albedo(Color(erase_color, 0.8));
} else if (mode_buttons_group->get_pressed_button() == pick_mode_button) {
cursor_inner_mat->set_albedo(Color(pick_color, 0.2));
cursor_outer_mat->set_albedo(Color(pick_color, 0.8));
// Make the cursor translucent so that it can be distinguished from already-placed tiles.
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index ff52a67dbc7c..7d318e167c77 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -82,6 +82,8 @@ bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
Array meshes = p_value;
+ const RID scenario = get_world_3d()->get_scenario();
for (int i = 0; i < meshes.size(); i++) {
BakedMesh bm;
bm.mesh = meshes[i];
@@ -90,7 +92,7 @@ bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
RS::get_singleton()->instance_set_base(bm.instance, bm.mesh->get_rid());
RS::get_singleton()->instance_attach_object_instance_id(bm.instance, get_instance_id());
+ RS::get_singleton()->instance_set_scenario(bm.instance, scenario);
RS::get_singleton()->instance_set_transform(bm.instance, get_global_transform());
baked_meshes.push_back(bm);
@@ -621,6 +623,18 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
HashMap<int, List<Pair<Transform3D, IndexKey>>> multimesh_items;
+ RID scenario;
+ RID navigation_map;
+ if (is_inside_tree()) {
+ scenario = get_world_3d()->get_scenario();
+ navigation_map = get_world_3d()->get_navigation_map();
+ }
for (const IndexKey &E : g.cells) {
ERR_CONTINUE(!cell_map.has(E));
const Cell &c = cell_map[E];
@@ -683,7 +697,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
nm.region = region;
@@ -698,7 +712,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
RS::get_singleton()->instance_set_base(nm.navigation_mesh_debug_instance, navigation_mesh_debug_rid);
if (is_inside_tree()) {
- RS::get_singleton()->instance_set_scenario(nm.navigation_mesh_debug_instance, get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_scenario(nm.navigation_mesh_debug_instance, scenario);
RS::get_singleton()->instance_set_transform(nm.navigation_mesh_debug_instance, get_global_transform() * nm.xform);
@@ -743,7 +757,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
RS::get_singleton()->instance_set_base(instance, mm);
- RS::get_singleton()->instance_set_scenario(instance, get_world_3d()->get_scenario());
RS::get_singleton()->instance_set_transform(instance, get_global_transform());
@@ -802,22 +816,27 @@ void GridMap::_update_physics_bodies_characteristics() {
void GridMap::_octant_enter_world(const OctantKey &p_key) {
ERR_FAIL_COND(!octant_map.has(p_key));
Octant &g = *octant_map[p_key];
+ const RID scenario = get_world_3d()->get_scenario();
#ifndef PHYSICS_3D_DISABLED
PhysicsServer3D::get_singleton()->body_set_state(g.static_body, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
PhysicsServer3D::get_singleton()->body_set_space(g.static_body, get_world_3d()->get_space());
if (g.collision_debug_instance.is_valid()) {
- RS::get_singleton()->instance_set_scenario(g.collision_debug_instance, get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_scenario(g.collision_debug_instance, scenario);
RS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform());
#endif // PHYSICS_3D_DISABLED
for (int i = 0; i < g.multimesh_instances.size(); i++) {
- RS::get_singleton()->instance_set_scenario(g.multimesh_instances[i].instance, get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_scenario(g.multimesh_instances[i].instance, scenario);
RS::get_singleton()->instance_set_transform(g.multimesh_instances[i].instance, get_global_transform());
#ifndef NAVIGATION_3D_DISABLED
+ const RID navigation_map = get_world_3d()->get_navigation_map();
if (bake_navigation && mesh_library.is_valid()) {
for (KeyValue<IndexKey, Octant::NavigationCell> &F : g.navigation_cell_ids) {
if (cell_map.has(F.key) && F.value.region.is_valid() == false) {
@@ -831,7 +850,7 @@ void GridMap::_octant_enter_world(const OctantKey &p_key) {
F.value.region = region; | [
"-\t\t\tcursor_instance = RenderingServer::get_singleton()->instance_create2(cursor_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());",
"-\t\t\t\tRS::get_singleton()->instance_set_scenario(bm.instance, get_world_3d()->get_scenario());",
"+\t\t\t\tRS::get_singleton()->instance_set_scenario(instance, scenario);"
] | [
39,
102,
149
] | {
"additions": 43,
"author": "smix8",
"deletions": 17,
"html_url": "https://github.com/godotengine/godot/pull/105563",
"issue_id": 105563,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 105563,
"repo": "godotengine/godot",
"title": "Optimize GridMap rendering scenario quadruple-getters",
"total_changes": 60
} |
729 | diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index ff52a67dbc7c..f5fcc2aa8a40 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -354,10 +354,7 @@ void GridMap::set_cell_item(const Vector3i &p_position, int p_item, int p_rot) {
key.y = p_position.y;
key.z = p_position.z;
- OctantKey ok;
- ok.x = p_position.x / octant_size;
- ok.y = p_position.y / octant_size;
- ok.z = p_position.z / octant_size;
+ const OctantKey ok = get_octant_key_from_cell_coords(p_position);
if (p_item < 0) {
//erase
@@ -521,6 +518,32 @@ int GridMap::get_orthogonal_index_from_basis(const Basis &p_basis) const {
return 0;
}
+GridMap::OctantKey GridMap::get_octant_key_from_index_key(const IndexKey &p_index_key) const {
+ const int x = p_index_key.x > 0 ? p_index_key.x / octant_size : (p_index_key.x - (octant_size - 1)) / octant_size;
+ const int y = p_index_key.y > 0 ? p_index_key.y / octant_size : (p_index_key.y - (octant_size - 1)) / octant_size;
+ const int z = p_index_key.z > 0 ? p_index_key.z / octant_size : (p_index_key.z - (octant_size - 1)) / octant_size;
+
+ OctantKey ok;
+ ok.key = 0;
+ ok.x = x;
+ ok.y = y;
+ ok.z = z;
+ return ok;
+}
+
+GridMap::OctantKey GridMap::get_octant_key_from_cell_coords(const Vector3i &p_cell_coords) const {
+ const int x = p_cell_coords.x > 0 ? p_cell_coords.x / octant_size : (p_cell_coords.x - (octant_size - 1)) / octant_size;
+ const int y = p_cell_coords.y > 0 ? p_cell_coords.y / octant_size : (p_cell_coords.y - (octant_size - 1)) / octant_size;
+ const int z = p_cell_coords.z > 0 ? p_cell_coords.z / octant_size : (p_cell_coords.z - (octant_size - 1)) / octant_size;
+
+ OctantKey ok;
+ ok.key = 0;
+ ok.x = x;
+ ok.y = y;
+ ok.z = z;
+ return ok;
+}
+
Vector3i GridMap::local_to_map(const Vector3 &p_world_position) const {
Vector3 map_position = (p_world_position / cell_size).floor();
return Vector3i(map_position);
@@ -1320,10 +1343,7 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe
xform.set_origin(cellpos * cell_size + ofs);
xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
- OctantKey ok;
- ok.x = key.x / octant_size;
- ok.y = key.y / octant_size;
- ok.z = key.z / octant_size;
+ const OctantKey ok = get_octant_key_from_index_key(key);
if (!surface_map.has(ok)) {
surface_map[ok] = HashMap<Ref<Material>, Ref<SurfaceTool>>();
diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h
index b9db20fec2e9..fdad87a41a12 100644
--- a/modules/gridmap/grid_map.h
+++ b/modules/gridmap/grid_map.h
@@ -152,6 +152,9 @@ class GridMap : public Node3D {
OctantKey() {}
};
+ OctantKey get_octant_key_from_index_key(const IndexKey &p_index_key) const;
+ OctantKey get_octant_key_from_cell_coords(const Vector3i &p_cell_coords) const;
+
#ifndef PHYSICS_3D_DISABLED
uint32_t collision_layer = 1;
uint32_t collision_mask = 1;
| diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index ff52a67dbc7c..f5fcc2aa8a40 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -354,10 +354,7 @@ void GridMap::set_cell_item(const Vector3i &p_position, int p_item, int p_rot) {
key.y = p_position.y;
key.z = p_position.z;
- OctantKey ok;
- ok.x = p_position.x / octant_size;
- ok.y = p_position.y / octant_size;
- ok.z = p_position.z / octant_size;
+ const OctantKey ok = get_octant_key_from_cell_coords(p_position);
if (p_item < 0) {
//erase
@@ -521,6 +518,32 @@ int GridMap::get_orthogonal_index_from_basis(const Basis &p_basis) const {
return 0;
}
+GridMap::OctantKey GridMap::get_octant_key_from_index_key(const IndexKey &p_index_key) const {
+ const int x = p_index_key.x > 0 ? p_index_key.x / octant_size : (p_index_key.x - (octant_size - 1)) / octant_size;
+ const int y = p_index_key.y > 0 ? p_index_key.y / octant_size : (p_index_key.y - (octant_size - 1)) / octant_size;
+ const int z = p_index_key.z > 0 ? p_index_key.z / octant_size : (p_index_key.z - (octant_size - 1)) / octant_size;
+GridMap::OctantKey GridMap::get_octant_key_from_cell_coords(const Vector3i &p_cell_coords) const {
+ const int x = p_cell_coords.x > 0 ? p_cell_coords.x / octant_size : (p_cell_coords.x - (octant_size - 1)) / octant_size;
+ const int y = p_cell_coords.y > 0 ? p_cell_coords.y / octant_size : (p_cell_coords.y - (octant_size - 1)) / octant_size;
+ const int z = p_cell_coords.z > 0 ? p_cell_coords.z / octant_size : (p_cell_coords.z - (octant_size - 1)) / octant_size;
Vector3i GridMap::local_to_map(const Vector3 &p_world_position) const {
Vector3 map_position = (p_world_position / cell_size).floor();
return Vector3i(map_position);
@@ -1320,10 +1343,7 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe
xform.set_origin(cellpos * cell_size + ofs);
xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
- OctantKey ok;
- ok.x = key.x / octant_size;
- ok.z = key.z / octant_size;
+ const OctantKey ok = get_octant_key_from_index_key(key);
if (!surface_map.has(ok)) {
surface_map[ok] = HashMap<Ref<Material>, Ref<SurfaceTool>>();
diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h
index b9db20fec2e9..fdad87a41a12 100644
--- a/modules/gridmap/grid_map.h
+++ b/modules/gridmap/grid_map.h
@@ -152,6 +152,9 @@ class GridMap : public Node3D {
OctantKey() {}
};
+ OctantKey get_octant_key_from_index_key(const IndexKey &p_index_key) const;
+ OctantKey get_octant_key_from_cell_coords(const Vector3i &p_cell_coords) const;
#ifndef PHYSICS_3D_DISABLED
uint32_t collision_layer = 1;
uint32_t collision_mask = 1; | [
"-\t\tok.y = key.y / octant_size;"
] | [
55
] | {
"additions": 31,
"author": "smix8",
"deletions": 8,
"html_url": "https://github.com/godotengine/godot/pull/105329",
"issue_id": 105329,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 105329,
"repo": "godotengine/godot",
"title": "Fix GridMap OctantKey cell rasterization",
"total_changes": 39
} |
730 | diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp
index 4cde5a9646e6..1ec33b42f36a 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp
@@ -813,8 +813,8 @@ EditorPlugin::AfterGUIInput GridMapEditor::forward_spatial_input_event(Camera3D
for (const SetItem &si : set_items) {
undo_redo->add_do_method(node, "set_cell_item", si.position, si.new_value, si.new_orientation);
}
- for (List<SetItem>::Element *E = set_items.back(); E; E = E->prev()) {
- const SetItem &si = E->get();
+ for (uint32_t i = set_items.size(); i > 0; i--) {
+ const SetItem &si = set_items[i - 1];
undo_redo->add_undo_method(node, "set_cell_item", si.position, si.old_value, si.old_orientation);
}
@@ -1380,6 +1380,8 @@ GridMapEditor::GridMapEditor() {
toolbar->add_child(mode_buttons);
mode_buttons_group.instantiate();
+ viewport_shortcut_buttons.reserve(12);
+
transform_mode_button = memnew(Button);
transform_mode_button->set_theme_type_variation(SceneStringName(FlatButton));
transform_mode_button->set_toggle_mode(true);
diff --git a/modules/gridmap/editor/grid_map_editor_plugin.h b/modules/gridmap/editor/grid_map_editor_plugin.h
index be42650f1529..5323b10ca62b 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.h
+++ b/modules/gridmap/editor/grid_map_editor_plugin.h
@@ -74,7 +74,7 @@ class GridMapEditor : public VBoxContainer {
double accumulated_floor_delta = 0.0;
HBoxContainer *toolbar = nullptr;
- List<BaseButton *> viewport_shortcut_buttons;
+ TightLocalVector<BaseButton *> viewport_shortcut_buttons;
Ref<ButtonGroup> mode_buttons_group;
// mode
Button *transform_mode_button = nullptr;
@@ -110,7 +110,7 @@ class GridMapEditor : public VBoxContainer {
int old_orientation = 0;
};
- List<SetItem> set_items;
+ LocalVector<SetItem> set_items;
GridMap *node = nullptr;
Ref<MeshLibrary> mesh_library = nullptr;
@@ -139,7 +139,7 @@ class GridMapEditor : public VBoxContainer {
RID instance;
};
- List<ClipboardItem> clipboard_items;
+ LocalVector<ClipboardItem> clipboard_items;
Color default_color;
Color erase_color;
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index ff52a67dbc7c..44081132d309 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -32,6 +32,7 @@
#include "core/io/marshalls.h"
#include "core/math/convex_hull.h"
+#include "core/templates/a_hash_map.h"
#include "scene/resources/3d/box_shape_3d.h"
#include "scene/resources/3d/capsule_shape_3d.h"
#include "scene/resources/3d/concave_polygon_shape_3d.h"
@@ -619,7 +620,11 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
* and set said multimesh bounding box to one containing all cells which have this item
*/
- HashMap<int, List<Pair<Transform3D, IndexKey>>> multimesh_items;
+ struct MultiMeshItemPlacement {
+ Transform3D transform;
+ IndexKey index_key;
+ };
+ AHashMap<int, LocalVector<MultiMeshItemPlacement>> item_id_to_multimesh_item_placements;
for (const IndexKey &E : g.cells) {
ERR_CONTINUE(!cell_map.has(E));
@@ -639,14 +644,14 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
if (baked_meshes.is_empty()) {
if (mesh_library->get_item_mesh(c.item).is_valid()) {
- if (!multimesh_items.has(c.item)) {
- multimesh_items[c.item] = List<Pair<Transform3D, IndexKey>>();
+ if (!item_id_to_multimesh_item_placements.has(c.item)) {
+ item_id_to_multimesh_item_placements[c.item] = LocalVector<MultiMeshItemPlacement>();
}
- Pair<Transform3D, IndexKey> p;
- p.first = xform * mesh_library->get_item_mesh_transform(c.item);
- p.second = E;
- multimesh_items[c.item].push_back(p);
+ MultiMeshItemPlacement p;
+ p.transform = xform * mesh_library->get_item_mesh_transform(c.item);
+ p.index_key = E;
+ item_id_to_multimesh_item_placements[c.item].push_back(p);
}
}
@@ -717,7 +722,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
//update multimeshes, only if not baked
if (baked_meshes.is_empty()) {
- for (const KeyValue<int, List<Pair<Transform3D, IndexKey>>> &E : multimesh_items) {
+ for (const KeyValue<int, LocalVector<MultiMeshItemPlacement>> &E : item_id_to_multimesh_item_placements) {
Octant::MultimeshInstance mmi;
RID mm = RS::get_singleton()->multimesh_create();
@@ -725,14 +730,15 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
RS::get_singleton()->multimesh_set_mesh(mm, mesh_library->get_item_mesh(E.key)->get_rid());
int idx = 0;
- for (const Pair<Transform3D, IndexKey> &F : E.value) {
- RS::get_singleton()->multimesh_instance_set_transform(mm, idx, F.first);
+ const LocalVector<MultiMeshItemPlacement> &mm_item_placements = E.value;
+ for (const MultiMeshItemPlacement &mm_item_placement : mm_item_placements) {
+ RS::get_singleton()->multimesh_instance_set_transform(mm, idx, mm_item_placement.transform);
#ifdef TOOLS_ENABLED
Octant::MultimeshInstance::Item it;
it.index = idx;
- it.transform = F.first;
- it.key = F.second;
+ it.transform = mm_item_placement.transform;
+ it.key = mm_item_placement.index_key;
mmi.items.push_back(it);
#endif
@@ -1089,17 +1095,19 @@ void GridMap::_update_octants_callback() {
return;
}
- List<OctantKey> to_delete;
+ LocalVector<OctantKey> to_delete;
+ to_delete.reserve(octant_map.size());
for (const KeyValue<OctantKey, Octant *> &E : octant_map) {
if (_octant_update(E.key)) {
to_delete.push_back(E.key);
}
}
- while (to_delete.front()) {
- memdelete(octant_map[to_delete.front()->get()]);
- octant_map.erase(to_delete.front()->get());
- to_delete.pop_front();
+ while (!to_delete.is_empty()) {
+ const OctantKey &octantkey = to_delete[0];
+ memdelete(octant_map[octantkey]);
+ octant_map.erase(octantkey);
+ to_delete.remove_at_unordered(0);
}
_update_visibility();
| diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp
index 4cde5a9646e6..1ec33b42f36a 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp
@@ -813,8 +813,8 @@ EditorPlugin::AfterGUIInput GridMapEditor::forward_spatial_input_event(Camera3D
for (const SetItem &si : set_items) {
undo_redo->add_do_method(node, "set_cell_item", si.position, si.new_value, si.new_orientation);
- for (List<SetItem>::Element *E = set_items.back(); E; E = E->prev()) {
- const SetItem &si = E->get();
+ for (uint32_t i = set_items.size(); i > 0; i--) {
+ const SetItem &si = set_items[i - 1];
undo_redo->add_undo_method(node, "set_cell_item", si.position, si.old_value, si.old_orientation);
@@ -1380,6 +1380,8 @@ GridMapEditor::GridMapEditor() {
toolbar->add_child(mode_buttons);
mode_buttons_group.instantiate();
+ viewport_shortcut_buttons.reserve(12);
+
transform_mode_button = memnew(Button);
transform_mode_button->set_theme_type_variation(SceneStringName(FlatButton));
transform_mode_button->set_toggle_mode(true);
diff --git a/modules/gridmap/editor/grid_map_editor_plugin.h b/modules/gridmap/editor/grid_map_editor_plugin.h
index be42650f1529..5323b10ca62b 100644
--- a/modules/gridmap/editor/grid_map_editor_plugin.h
+++ b/modules/gridmap/editor/grid_map_editor_plugin.h
@@ -74,7 +74,7 @@ class GridMapEditor : public VBoxContainer {
double accumulated_floor_delta = 0.0;
HBoxContainer *toolbar = nullptr;
- List<BaseButton *> viewport_shortcut_buttons;
+ TightLocalVector<BaseButton *> viewport_shortcut_buttons;
Ref<ButtonGroup> mode_buttons_group;
// mode
Button *transform_mode_button = nullptr;
@@ -110,7 +110,7 @@ class GridMapEditor : public VBoxContainer {
int old_orientation = 0;
- List<SetItem> set_items;
+ LocalVector<SetItem> set_items;
GridMap *node = nullptr;
Ref<MeshLibrary> mesh_library = nullptr;
@@ -139,7 +139,7 @@ class GridMapEditor : public VBoxContainer {
RID instance;
- List<ClipboardItem> clipboard_items;
+ LocalVector<ClipboardItem> clipboard_items;
Color default_color;
Color erase_color;
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index ff52a67dbc7c..44081132d309 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -32,6 +32,7 @@
#include "core/io/marshalls.h"
#include "core/math/convex_hull.h"
+#include "core/templates/a_hash_map.h"
#include "scene/resources/3d/box_shape_3d.h"
#include "scene/resources/3d/capsule_shape_3d.h"
#include "scene/resources/3d/concave_polygon_shape_3d.h"
@@ -619,7 +620,11 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
* and set said multimesh bounding box to one containing all cells which have this item
*/
- HashMap<int, List<Pair<Transform3D, IndexKey>>> multimesh_items;
+ struct MultiMeshItemPlacement {
+ Transform3D transform;
+ IndexKey index_key;
+ };
+ AHashMap<int, LocalVector<MultiMeshItemPlacement>> item_id_to_multimesh_item_placements;
for (const IndexKey &E : g.cells) {
ERR_CONTINUE(!cell_map.has(E));
@@ -639,14 +644,14 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
if (baked_meshes.is_empty()) {
if (mesh_library->get_item_mesh(c.item).is_valid()) {
- if (!multimesh_items.has(c.item)) {
- multimesh_items[c.item] = List<Pair<Transform3D, IndexKey>>();
+ if (!item_id_to_multimesh_item_placements.has(c.item)) {
+ item_id_to_multimesh_item_placements[c.item] = LocalVector<MultiMeshItemPlacement>();
}
- Pair<Transform3D, IndexKey> p;
- p.first = xform * mesh_library->get_item_mesh_transform(c.item);
- p.second = E;
- multimesh_items[c.item].push_back(p);
+ MultiMeshItemPlacement p;
+ p.transform = xform * mesh_library->get_item_mesh_transform(c.item);
+ p.index_key = E;
+ item_id_to_multimesh_item_placements[c.item].push_back(p);
}
@@ -717,7 +722,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
//update multimeshes, only if not baked
if (baked_meshes.is_empty()) {
- for (const KeyValue<int, List<Pair<Transform3D, IndexKey>>> &E : multimesh_items) {
+ for (const KeyValue<int, LocalVector<MultiMeshItemPlacement>> &E : item_id_to_multimesh_item_placements) {
Octant::MultimeshInstance mmi;
RID mm = RS::get_singleton()->multimesh_create();
@@ -725,14 +730,15 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
RS::get_singleton()->multimesh_set_mesh(mm, mesh_library->get_item_mesh(E.key)->get_rid());
int idx = 0;
- for (const Pair<Transform3D, IndexKey> &F : E.value) {
- RS::get_singleton()->multimesh_instance_set_transform(mm, idx, F.first);
+ const LocalVector<MultiMeshItemPlacement> &mm_item_placements = E.value;
+ RS::get_singleton()->multimesh_instance_set_transform(mm, idx, mm_item_placement.transform);
#ifdef TOOLS_ENABLED
Octant::MultimeshInstance::Item it;
it.index = idx;
- it.transform = F.first;
- it.key = F.second;
+ it.transform = mm_item_placement.transform;
+ it.key = mm_item_placement.index_key;
mmi.items.push_back(it);
#endif
@@ -1089,17 +1095,19 @@ void GridMap::_update_octants_callback() {
return;
+ LocalVector<OctantKey> to_delete;
+ to_delete.reserve(octant_map.size());
for (const KeyValue<OctantKey, Octant *> &E : octant_map) {
if (_octant_update(E.key)) {
to_delete.push_back(E.key);
- while (to_delete.front()) {
- memdelete(octant_map[to_delete.front()->get()]);
- octant_map.erase(to_delete.front()->get());
- to_delete.pop_front();
+ while (!to_delete.is_empty()) {
+ const OctantKey &octantkey = to_delete[0];
+ memdelete(octant_map[octantkey]);
+ octant_map.erase(octantkey);
+ to_delete.remove_at_unordered(0);
_update_visibility(); | [
"+\t\t\tfor (const MultiMeshItemPlacement &mm_item_placement : mm_item_placements) {",
"-\tList<OctantKey> to_delete;"
] | [
117,
134
] | {
"additions": 32,
"author": "smix8",
"deletions": 22,
"html_url": "https://github.com/godotengine/godot/pull/105565",
"issue_id": 105565,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 105565,
"repo": "godotengine/godot",
"title": "Replace GridMap legacy use of `List` with `LocalVector`",
"total_changes": 54
} |
731 | diff --git a/platform/android/java/build.gradle b/platform/android/java/build.gradle
index 3dd8bbed8821..bbdf03612c3b 100644
--- a/platform/android/java/build.gradle
+++ b/platform/android/java/build.gradle
@@ -79,7 +79,7 @@ def templateExcludedBuildTask() {
// We exclude these gradle tasks so we can run the scons command manually.
def excludedTasks = []
if (excludeSconsBuildTasks()) {
- logger.lifecycle("Excluding Android studio build tasks")
+ logger.info("Excluding Android studio build tasks")
for (String flavor : supportedFlavors) {
String[] supportedBuildTypes = supportedFlavorsBuildTypes[flavor]
for (String buildType : supportedBuildTypes) {
@@ -206,7 +206,7 @@ def generateBuildTasks(String flavor = "template", String edition = "standard",
}
}
} else {
- logger.lifecycle("No native shared libs for target $target. Skipping build.")
+ logger.info("No native shared libs for target $target. Skipping build.")
}
}
diff --git a/platform/android/java/lib/build.gradle b/platform/android/java/lib/build.gradle
index f273105efcbe..371a1b4bff92 100644
--- a/platform/android/java/lib/build.gradle
+++ b/platform/android/java/lib/build.gradle
@@ -5,6 +5,7 @@ plugins {
ext {
PUBLISH_ARTIFACT_ID = 'godot'
+ TOOLS_PUBLISH_ARTIFACT_ID = 'godot-tools'
}
apply from: "../scripts/publish-module.gradle"
@@ -185,5 +186,9 @@ android {
withSourcesJar()
withJavadocJar()
}
+ singleVariant("editorRelease") {
+ withSourcesJar()
+ withJavadocJar()
+ }
}
}
diff --git a/platform/android/java/scripts/publish-module.gradle b/platform/android/java/scripts/publish-module.gradle
index 32b749e493d6..d0fec9af19d0 100644
--- a/platform/android/java/scripts/publish-module.gradle
+++ b/platform/android/java/scripts/publish-module.gradle
@@ -19,7 +19,55 @@ afterEvaluate {
// Mostly self-explanatory metadata
pom {
name = PUBLISH_ARTIFACT_ID
- description = 'Godot Engine Android Library'
+ description = 'Godot Engine Android Library - Template Build'
+ url = 'https://godotengine.org/'
+ licenses {
+ license {
+ name = 'MIT License'
+ url = 'https://github.com/godotengine/godot/blob/master/LICENSE.txt'
+ }
+ }
+ developers {
+ developer {
+ id = 'm4gr3d'
+ name = 'Fredia Huya-Kouadio'
+ email = '[email protected]'
+ }
+ developer {
+ id = 'reduz'
+ name = 'Juan Linietsky'
+ email = '[email protected]'
+ }
+ developer {
+ id = 'akien-mga'
+ name = 'Rémi Verschelde'
+ email = '[email protected]'
+ }
+ // Add all other devs here...
+ }
+
+ // Version control info - if you're using GitHub, follow the
+ // format as seen here
+ scm {
+ connection = 'scm:git:github.com/godotengine/godot.git'
+ developerConnection = 'scm:git:ssh://github.com/godotengine/godot.git'
+ url = 'https://github.com/godotengine/godot/tree/master'
+ }
+ }
+ }
+ toolsRelease(MavenPublication) {
+ from components.editorRelease
+
+ // The coordinates of the library, being set from variables that
+ // we'll set up later
+ groupId ossrhGroupId
+ artifactId TOOLS_PUBLISH_ARTIFACT_ID
+ version PUBLISH_VERSION
+
+ // Mostly self-explanatory metadata
+ pom {
+ name = TOOLS_PUBLISH_ARTIFACT_ID
+ description = 'Godot Engine Tools Android Library - Editor Build'
url = 'https://godotengine.org/'
licenses {
license {
| diff --git a/platform/android/java/build.gradle b/platform/android/java/build.gradle
index 3dd8bbed8821..bbdf03612c3b 100644
--- a/platform/android/java/build.gradle
+++ b/platform/android/java/build.gradle
@@ -79,7 +79,7 @@ def templateExcludedBuildTask() {
// We exclude these gradle tasks so we can run the scons command manually.
def excludedTasks = []
if (excludeSconsBuildTasks()) {
- logger.lifecycle("Excluding Android studio build tasks")
+ logger.info("Excluding Android studio build tasks")
for (String flavor : supportedFlavors) {
String[] supportedBuildTypes = supportedFlavorsBuildTypes[flavor]
for (String buildType : supportedBuildTypes) {
@@ -206,7 +206,7 @@ def generateBuildTasks(String flavor = "template", String edition = "standard",
}
}
} else {
- logger.lifecycle("No native shared libs for target $target. Skipping build.")
+ logger.info("No native shared libs for target $target. Skipping build.")
diff --git a/platform/android/java/lib/build.gradle b/platform/android/java/lib/build.gradle
index f273105efcbe..371a1b4bff92 100644
--- a/platform/android/java/lib/build.gradle
+++ b/platform/android/java/lib/build.gradle
@@ -5,6 +5,7 @@ plugins {
ext {
PUBLISH_ARTIFACT_ID = 'godot'
+ TOOLS_PUBLISH_ARTIFACT_ID = 'godot-tools'
apply from: "../scripts/publish-module.gradle"
@@ -185,5 +186,9 @@ android {
withSourcesJar()
withJavadocJar()
+ singleVariant("editorRelease") {
+ withSourcesJar()
+ withJavadocJar()
+ }
diff --git a/platform/android/java/scripts/publish-module.gradle b/platform/android/java/scripts/publish-module.gradle
index 32b749e493d6..d0fec9af19d0 100644
--- a/platform/android/java/scripts/publish-module.gradle
+++ b/platform/android/java/scripts/publish-module.gradle
@@ -19,7 +19,55 @@ afterEvaluate {
// Mostly self-explanatory metadata
pom {
name = PUBLISH_ARTIFACT_ID
- description = 'Godot Engine Android Library'
+ description = 'Godot Engine Android Library - Template Build'
+ url = 'https://godotengine.org/'
+ licenses {
+ license {
+ name = 'MIT License'
+ developers {
+ name = 'Fredia Huya-Kouadio'
+ email = '[email protected]'
+ id = 'reduz'
+ name = 'Juan Linietsky'
+ email = '[email protected]'
+ id = 'akien-mga'
+ name = 'Rémi Verschelde'
+ email = '[email protected]'
+ // Add all other devs here...
+ // Version control info - if you're using GitHub, follow the
+ // format as seen here
+ scm {
+ }
+ toolsRelease(MavenPublication) {
+ from components.editorRelease
+ // The coordinates of the library, being set from variables that
+ // we'll set up later
+ artifactId TOOLS_PUBLISH_ARTIFACT_ID
+ version PUBLISH_VERSION
+ // Mostly self-explanatory metadata
+ pom {
+ name = TOOLS_PUBLISH_ARTIFACT_ID
+ description = 'Godot Engine Tools Android Library - Editor Build'
url = 'https://godotengine.org/'
licenses {
license { | [
"+ url = 'https://github.com/godotengine/godot/blob/master/LICENSE.txt'",
"+ id = 'm4gr3d'",
"+ connection = 'scm:git:github.com/godotengine/godot.git'",
"+ developerConnection = 'scm:git:ssh://github.com/godotengine/godot.git'",
"+ url = 'https://github.com/godotengine/godot/tree/master'",
"+ }",
"+ groupId ossrhGroupId"
] | [
58,
63,
83,
84,
85,
87,
94
] | {
"additions": 56,
"author": "m4gr3d",
"deletions": 3,
"html_url": "https://github.com/godotengine/godot/pull/104819",
"issue_id": 104819,
"merged_at": "2025-04-16T15:49:51Z",
"omission_probability": 0.1,
"pr_number": 104819,
"repo": "godotengine/godot",
"title": "Add maven publishing configuration for Godot tools",
"total_changes": 59
} |
732 | diff --git a/editor/project_settings_editor.cpp b/editor/project_settings_editor.cpp
index db5113fa7035..cf9f8080b362 100644
--- a/editor/project_settings_editor.cpp
+++ b/editor/project_settings_editor.cpp
@@ -42,8 +42,6 @@
#include "scene/gui/check_button.h"
#include "servers/movie_writer/movie_writer.h"
-ProjectSettingsEditor *ProjectSettingsEditor::singleton = nullptr;
-
void ProjectSettingsEditor::connect_filesystem_dock_signals(FileSystemDock *p_fs_dock) {
localization_editor->connect_filesystem_dock_signals(p_fs_dock);
group_settings->connect_filesystem_dock_signals(p_fs_dock);
@@ -179,35 +177,45 @@ void ProjectSettingsEditor::_property_box_changed(const String &p_text) {
}
void ProjectSettingsEditor::_feature_selected(int p_index) {
- Vector<String> t = property_box->get_text().strip_edges().split(".", true, 1);
- const String feature = p_index ? "." + feature_box->get_item_text(p_index) : "";
- property_box->set_text(t[0] + feature);
+ const String property = property_box->get_text().strip_edges().get_slicec('.', 0);
+ if (p_index == FEATURE_ALL) {
+ property_box->set_text(property);
+ } else if (p_index == FEATURE_CUSTOM) {
+ property_box->set_text(property + ".custom");
+ const int len = property.length() + 1;
+ property_box->select(len);
+ property_box->set_caret_column(len);
+ property_box->grab_focus();
+ } else {
+ property_box->set_text(property + "." + feature_box->get_item_text(p_index));
+ };
_update_property_box();
}
void ProjectSettingsEditor::_update_property_box() {
const String setting = _get_setting_name();
- const Vector<String> t = setting.split(".", true, 1);
- const String &name = t[0];
- const String feature = (t.size() == 2) ? t[1] : "";
- bool feature_invalid = (t.size() == 2) && (t[1].is_empty());
+ int slices = setting.get_slice_count(".");
+ const String name = setting.get_slicec('.', 0);
+ const String feature = setting.get_slicec('.', 1);
+ bool feature_invalid = slices > 2 || (slices == 2 && feature.is_empty());
add_button->set_disabled(true);
del_button->set_disabled(true);
- if (!feature.is_empty()) {
- feature_invalid = true;
- for (int i = 1; i < feature_box->get_item_count(); i++) {
+ if (feature.is_empty() || feature_invalid) {
+ feature_box->select(FEATURE_ALL);
+ } else {
+ bool is_custom = true;
+ for (int i = FEATURE_FIRST; i < feature_box->get_item_count(); i++) {
if (feature == feature_box->get_item_text(i)) {
- feature_invalid = false;
+ is_custom = false;
feature_box->select(i);
break;
}
}
- }
-
- if (feature.is_empty() || feature_invalid) {
- feature_box->select(0);
+ if (is_custom) {
+ feature_box->select(FEATURE_CUSTOM);
+ }
}
if (property_box->get_text().is_empty()) {
@@ -330,8 +338,11 @@ void ProjectSettingsEditor::_add_feature_overrides() {
}
feature_box->clear();
- feature_box->add_item(TTR("(All)"), 0); // So it is always on top.
- int id = 1;
+ feature_box->add_item(TTR("(All)"), FEATURE_ALL); // So it is always on top.
+ feature_box->add_item(TTR("Custom"), FEATURE_CUSTOM);
+ feature_box->add_separator();
+
+ int id = FEATURE_FIRST;
for (const String &E : presets) {
feature_box->add_item(E, id++);
}
diff --git a/editor/project_settings_editor.h b/editor/project_settings_editor.h
index a6f846ca8adc..9506458ea51b 100644
--- a/editor/project_settings_editor.h
+++ b/editor/project_settings_editor.h
@@ -49,7 +49,14 @@ class FileSystemDock;
class ProjectSettingsEditor : public AcceptDialog {
GDCLASS(ProjectSettingsEditor, AcceptDialog);
- static ProjectSettingsEditor *singleton;
+ inline static ProjectSettingsEditor *singleton = nullptr;
+
+ enum {
+ FEATURE_ALL,
+ FEATURE_CUSTOM,
+ FEATURE_FIRST,
+ };
+
ProjectSettings *ps = nullptr;
Timer *timer = nullptr;
| diff --git a/editor/project_settings_editor.cpp b/editor/project_settings_editor.cpp
index db5113fa7035..cf9f8080b362 100644
--- a/editor/project_settings_editor.cpp
+++ b/editor/project_settings_editor.cpp
@@ -42,8 +42,6 @@
#include "scene/gui/check_button.h"
#include "servers/movie_writer/movie_writer.h"
void ProjectSettingsEditor::connect_filesystem_dock_signals(FileSystemDock *p_fs_dock) {
localization_editor->connect_filesystem_dock_signals(p_fs_dock);
group_settings->connect_filesystem_dock_signals(p_fs_dock);
@@ -179,35 +177,45 @@ void ProjectSettingsEditor::_property_box_changed(const String &p_text) {
void ProjectSettingsEditor::_feature_selected(int p_index) {
- Vector<String> t = property_box->get_text().strip_edges().split(".", true, 1);
- const String feature = p_index ? "." + feature_box->get_item_text(p_index) : "";
- property_box->set_text(t[0] + feature);
+ const String property = property_box->get_text().strip_edges().get_slicec('.', 0);
+ if (p_index == FEATURE_ALL) {
+ property_box->set_text(property);
+ } else if (p_index == FEATURE_CUSTOM) {
+ property_box->set_text(property + ".custom");
+ const int len = property.length() + 1;
+ property_box->select(len);
+ property_box->set_caret_column(len);
+ property_box->grab_focus();
+ property_box->set_text(property + "." + feature_box->get_item_text(p_index));
_update_property_box();
void ProjectSettingsEditor::_update_property_box() {
const String setting = _get_setting_name();
- const Vector<String> t = setting.split(".", true, 1);
- const String &name = t[0];
- const String feature = (t.size() == 2) ? t[1] : "";
- bool feature_invalid = (t.size() == 2) && (t[1].is_empty());
+ int slices = setting.get_slice_count(".");
+ const String name = setting.get_slicec('.', 0);
+ const String feature = setting.get_slicec('.', 1);
+ bool feature_invalid = slices > 2 || (slices == 2 && feature.is_empty());
add_button->set_disabled(true);
del_button->set_disabled(true);
- if (!feature.is_empty()) {
- feature_invalid = true;
- for (int i = 1; i < feature_box->get_item_count(); i++) {
+ if (feature.is_empty() || feature_invalid) {
+ feature_box->select(FEATURE_ALL);
+ bool is_custom = true;
+ for (int i = FEATURE_FIRST; i < feature_box->get_item_count(); i++) {
if (feature == feature_box->get_item_text(i)) {
- feature_invalid = false;
+ is_custom = false;
feature_box->select(i);
break;
}
}
- if (feature.is_empty() || feature_invalid) {
- feature_box->select(0);
+ if (is_custom) {
+ feature_box->select(FEATURE_CUSTOM);
if (property_box->get_text().is_empty()) {
@@ -330,8 +338,11 @@ void ProjectSettingsEditor::_add_feature_overrides() {
feature_box->clear();
- feature_box->add_item(TTR("(All)"), 0); // So it is always on top.
- int id = 1;
+ feature_box->add_item(TTR("(All)"), FEATURE_ALL); // So it is always on top.
+ feature_box->add_item(TTR("Custom"), FEATURE_CUSTOM);
+ feature_box->add_separator();
+ int id = FEATURE_FIRST;
for (const String &E : presets) {
feature_box->add_item(E, id++);
diff --git a/editor/project_settings_editor.h b/editor/project_settings_editor.h
index a6f846ca8adc..9506458ea51b 100644
--- a/editor/project_settings_editor.h
+++ b/editor/project_settings_editor.h
@@ -49,7 +49,14 @@ class FileSystemDock;
class ProjectSettingsEditor : public AcceptDialog {
GDCLASS(ProjectSettingsEditor, AcceptDialog);
- static ProjectSettingsEditor *singleton;
+ inline static ProjectSettingsEditor *singleton = nullptr;
+ enum {
+ FEATURE_ALL,
+ FEATURE_CUSTOM,
+ FEATURE_FIRST,
ProjectSettings *ps = nullptr;
Timer *timer = nullptr; | [
"-ProjectSettingsEditor *ProjectSettingsEditor::singleton = nullptr;",
"-\t}",
"+\t\t}"
] | [
8,
64,
70
] | {
"additions": 38,
"author": "KoBeWi",
"deletions": 20,
"html_url": "https://github.com/godotengine/godot/pull/105307",
"issue_id": 105307,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 105307,
"repo": "godotengine/godot",
"title": "Support custom features in project settings dialog",
"total_changes": 58
} |
733 | diff --git a/scene/gui/color_mode.cpp b/scene/gui/color_mode.cpp
index 5f58a16d50fe..ccf2d03caa3a 100644
--- a/scene/gui/color_mode.cpp
+++ b/scene/gui/color_mode.cpp
@@ -43,12 +43,6 @@ String ColorModeRGB::get_slider_label(int idx) const {
return labels[idx];
}
-float ColorModeRGB::get_slider_max(int idx) const {
- ERR_FAIL_INDEX_V_MSG(idx, 4, 0, "Couldn't get slider max value.");
- Color color = color_picker->get_pick_color();
- return next_power_of_2(MAX(255, color.components[idx] * 255.0)) - 1;
-}
-
float ColorModeRGB::get_slider_value(int idx) const {
ERR_FAIL_INDEX_V_MSG(idx, 4, 0, "Couldn't get slider value.");
return color_picker->get_pick_color().components[idx] * 255;
diff --git a/scene/gui/color_mode.h b/scene/gui/color_mode.h
index c035fe6f65a3..4c73967e15fb 100644
--- a/scene/gui/color_mode.h
+++ b/scene/gui/color_mode.h
@@ -46,6 +46,7 @@ class ColorMode {
virtual float get_spinbox_arrow_step() const { return get_slider_step(); }
virtual String get_slider_label(int idx) const = 0;
virtual float get_slider_max(int idx) const = 0;
+ virtual bool get_allow_greater() const { return false; }
virtual float get_slider_value(int idx) const = 0;
virtual Color get_color() const = 0;
@@ -92,7 +93,8 @@ class ColorModeRGB : public ColorMode {
virtual float get_slider_step() const override { return 1; }
virtual String get_slider_label(int idx) const override;
- virtual float get_slider_max(int idx) const override;
+ virtual float get_slider_max(int idx) const override { return 255; }
+ virtual bool get_allow_greater() const override { return true; }
virtual float get_slider_value(int idx) const override;
virtual Color get_color() const override;
@@ -114,6 +116,7 @@ class ColorModeRAW : public ColorMode {
virtual float get_spinbox_arrow_step() const override { return 0.01; }
virtual String get_slider_label(int idx) const override;
virtual float get_slider_max(int idx) const override;
+ virtual bool get_allow_greater() const override { return true; }
virtual float get_slider_value(int idx) const override;
virtual Color get_color() const override;
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index 27539c906456..9f5d1a6dfbf6 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -675,8 +675,9 @@ void ColorPicker::_update_color(bool p_update_sliders) {
for (int i = 0; i < current_slider_count; i++) {
sliders[i]->set_max(modes[current_mode]->get_slider_max(i));
sliders[i]->set_step(step);
- values[i]->set_custom_arrow_step(spinbox_arrow_step);
sliders[i]->set_value(modes[current_mode]->get_slider_value(i));
+ values[i]->set_custom_arrow_step(spinbox_arrow_step);
+ values[i]->set_allow_greater(modes[current_mode]->get_allow_greater());
}
alpha_slider->set_max(modes[current_mode]->get_slider_max(current_slider_count));
alpha_slider->set_step(step);
| diff --git a/scene/gui/color_mode.cpp b/scene/gui/color_mode.cpp
index 5f58a16d50fe..ccf2d03caa3a 100644
--- a/scene/gui/color_mode.cpp
+++ b/scene/gui/color_mode.cpp
@@ -43,12 +43,6 @@ String ColorModeRGB::get_slider_label(int idx) const {
return labels[idx];
}
-float ColorModeRGB::get_slider_max(int idx) const {
- ERR_FAIL_INDEX_V_MSG(idx, 4, 0, "Couldn't get slider max value.");
- Color color = color_picker->get_pick_color();
- return next_power_of_2(MAX(255, color.components[idx] * 255.0)) - 1;
-}
-
float ColorModeRGB::get_slider_value(int idx) const {
ERR_FAIL_INDEX_V_MSG(idx, 4, 0, "Couldn't get slider value.");
return color_picker->get_pick_color().components[idx] * 255;
diff --git a/scene/gui/color_mode.h b/scene/gui/color_mode.h
index c035fe6f65a3..4c73967e15fb 100644
--- a/scene/gui/color_mode.h
+++ b/scene/gui/color_mode.h
@@ -46,6 +46,7 @@ class ColorMode {
virtual float get_spinbox_arrow_step() const { return get_slider_step(); }
virtual String get_slider_label(int idx) const = 0;
virtual float get_slider_max(int idx) const = 0;
+ virtual bool get_allow_greater() const { return false; }
virtual float get_slider_value(int idx) const = 0;
virtual Color get_color() const = 0;
@@ -92,7 +93,8 @@ class ColorModeRGB : public ColorMode {
virtual float get_slider_step() const override { return 1; }
- virtual float get_slider_max(int idx) const override;
+ virtual float get_slider_max(int idx) const override { return 255; }
@@ -114,6 +116,7 @@ class ColorModeRAW : public ColorMode {
virtual float get_spinbox_arrow_step() const override { return 0.01; }
virtual float get_slider_max(int idx) const override;
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index 27539c906456..9f5d1a6dfbf6 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -675,8 +675,9 @@ void ColorPicker::_update_color(bool p_update_sliders) {
for (int i = 0; i < current_slider_count; i++) {
sliders[i]->set_max(modes[current_mode]->get_slider_max(i));
sliders[i]->set_step(step);
sliders[i]->set_value(modes[current_mode]->get_slider_value(i));
+ values[i]->set_custom_arrow_step(spinbox_arrow_step);
+ values[i]->set_allow_greater(modes[current_mode]->get_allow_greater());
}
alpha_slider->set_max(modes[current_mode]->get_slider_max(current_slider_count));
alpha_slider->set_step(step); | [
"-\t\t\tvalues[i]->set_custom_arrow_step(spinbox_arrow_step);"
] | [
55
] | {
"additions": 6,
"author": "KoBeWi",
"deletions": 8,
"html_url": "https://github.com/godotengine/godot/pull/102240",
"issue_id": 102240,
"merged_at": "2025-04-22T15:46:13Z",
"omission_probability": 0.1,
"pr_number": 102240,
"repo": "godotengine/godot",
"title": "Fix ColorPicker sliders in overbright RGB",
"total_changes": 14
} |
734 | diff --git a/core/templates/rid_owner.h b/core/templates/rid_owner.h
index 3ff34c407e4b..f87134092484 100644
--- a/core/templates/rid_owner.h
+++ b/core/templates/rid_owner.h
@@ -33,7 +33,7 @@
#include "core/os/memory.h"
#include "core/os/mutex.h"
#include "core/string/print_string.h"
-#include "core/templates/list.h"
+#include "core/templates/local_vector.h"
#include "core/templates/rid.h"
#include "core/templates/safe_refcount.h"
@@ -382,19 +382,21 @@ class RID_Alloc : public RID_AllocBase {
_FORCE_INLINE_ uint32_t get_rid_count() const {
return alloc_count;
}
- void get_owned_list(List<RID> *p_owned) const {
+ LocalVector<RID> get_owned_list() const {
+ LocalVector<RID> owned;
if constexpr (THREAD_SAFE) {
mutex.lock();
}
for (size_t i = 0; i < max_alloc; i++) {
uint64_t validator = chunks[i / elements_in_chunk][i % elements_in_chunk].validator;
if (validator != 0xFFFFFFFF) {
- p_owned->push_back(_make_from_id((validator << 32) | i));
+ owned.push_back(_make_from_id((validator << 32) | i));
}
}
if constexpr (THREAD_SAFE) {
mutex.unlock();
}
+ return owned;
}
//used for fast iteration in the elements or RIDs
@@ -506,8 +508,8 @@ class RID_PtrOwner {
return alloc.get_rid_count();
}
- _FORCE_INLINE_ void get_owned_list(List<RID> *p_owned) const {
- return alloc.get_owned_list(p_owned);
+ _FORCE_INLINE_ LocalVector<RID> get_owned_list() const {
+ return alloc.get_owned_list();
}
void fill_owned_buffer(RID *p_rid_buffer) const {
@@ -562,8 +564,8 @@ class RID_Owner {
return alloc.get_rid_count();
}
- _FORCE_INLINE_ void get_owned_list(List<RID> *p_owned) const {
- return alloc.get_owned_list(p_owned);
+ _FORCE_INLINE_ LocalVector<RID> get_owned_list() const {
+ return alloc.get_owned_list();
}
void fill_owned_buffer(RID *p_rid_buffer) const {
alloc.fill_owned_buffer(p_rid_buffer);
diff --git a/drivers/gles3/shader_gles3.cpp b/drivers/gles3/shader_gles3.cpp
index d7070d52f4aa..2411cd3025ed 100644
--- a/drivers/gles3/shader_gles3.cpp
+++ b/drivers/gles3/shader_gles3.cpp
@@ -841,13 +841,11 @@ bool ShaderGLES3::shader_cache_save_compressed_zstd = true;
bool ShaderGLES3::shader_cache_save_debug = true;
ShaderGLES3::~ShaderGLES3() {
- List<RID> remaining;
- version_owner.get_owned_list(&remaining);
+ LocalVector<RID> remaining = version_owner.get_owned_list();
if (remaining.size()) {
ERR_PRINT(itos(remaining.size()) + " shaders of type " + name + " were never freed");
- while (remaining.size()) {
- version_free(remaining.front()->get());
- remaining.pop_front();
+ for (RID &rid : remaining) {
+ version_free(rid);
}
}
}
diff --git a/drivers/gles3/storage/texture_storage.cpp b/drivers/gles3/storage/texture_storage.cpp
index b52b6a8f1984..7035a79d5e51 100644
--- a/drivers/gles3/storage/texture_storage.cpp
+++ b/drivers/gles3/storage/texture_storage.cpp
@@ -1470,10 +1470,7 @@ void TextureStorage::texture_set_detect_roughness_callback(RID p_texture, RS::Te
}
void TextureStorage::texture_debug_usage(List<RS::TextureInfo> *r_info) {
- List<RID> textures;
- texture_owner.get_owned_list(&textures);
-
- for (const RID &rid : textures) {
+ for (const RID &rid : texture_owner.get_owned_list()) {
Texture *t = texture_owner.get_or_null(rid);
if (!t) {
continue;
diff --git a/modules/navigation_2d/2d/godot_navigation_server_2d.cpp b/modules/navigation_2d/2d/godot_navigation_server_2d.cpp
index 2b4f898dafdf..048208f5e527 100644
--- a/modules/navigation_2d/2d/godot_navigation_server_2d.cpp
+++ b/modules/navigation_2d/2d/godot_navigation_server_2d.cpp
@@ -32,6 +32,7 @@
#include "core/os/mutex.h"
#include "scene/main/node.h"
+#include <cstdint>
#ifdef CLIPPER2_ENABLED
#include "nav_mesh_generator_2d.h"
@@ -193,11 +194,12 @@ void GodotNavigationServer2D::add_command(SetCommand2D *p_command) {
TypedArray<RID> GodotNavigationServer2D::get_maps() const {
TypedArray<RID> all_map_rids;
- List<RID> maps_owned;
- map_owner.get_owned_list(&maps_owned);
- if (maps_owned.size()) {
- for (const RID &E : maps_owned) {
- all_map_rids.push_back(E);
+ LocalVector<RID> maps_owned = map_owner.get_owned_list();
+ uint32_t map_count = maps_owned.size();
+ if (map_count) {
+ all_map_rids.resize(map_count);
+ for (uint32_t i = 0; i < map_count; i++) {
+ all_map_rids[i] = maps_owned[i];
}
}
return all_map_rids;
diff --git a/modules/navigation_3d/3d/godot_navigation_server_3d.cpp b/modules/navigation_3d/3d/godot_navigation_server_3d.cpp
index 498566a04e79..d4469d3c3eac 100644
--- a/modules/navigation_3d/3d/godot_navigation_server_3d.cpp
+++ b/modules/navigation_3d/3d/godot_navigation_server_3d.cpp
@@ -94,11 +94,12 @@ void GodotNavigationServer3D::add_command(SetCommand3D *command) {
TypedArray<RID> GodotNavigationServer3D::get_maps() const {
TypedArray<RID> all_map_rids;
- List<RID> maps_owned;
- map_owner.get_owned_list(&maps_owned);
- if (maps_owned.size()) {
- for (const RID &E : maps_owned) {
- all_map_rids.push_back(E);
+ LocalVector<RID> maps_owned = map_owner.get_owned_list();
+ uint32_t map_count = maps_owned.size();
+ if (map_count) {
+ all_map_rids.resize(map_count);
+ for (uint32_t i = 0; i < map_count; i++) {
+ all_map_rids[i] = maps_owned[i];
}
}
return all_map_rids;
diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cpp
index 4e0a0535c44a..befc3ebe2021 100644
--- a/modules/openxr/openxr_api.cpp
+++ b/modules/openxr/openxr_api.cpp
@@ -1415,9 +1415,7 @@ bool OpenXRAPI::on_state_synchronized() {
print_verbose("On state synchronized");
// Just in case, see if we already have active trackers...
- List<RID> trackers;
- tracker_owner.get_owned_list(&trackers);
- for (const RID &tracker : trackers) {
+ for (const RID &tracker : tracker_owner.get_owned_list()) {
tracker_check_profile(tracker);
}
@@ -2066,9 +2064,7 @@ bool OpenXRAPI::poll_events() {
XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent;
- List<RID> trackers;
- tracker_owner.get_owned_list(&trackers);
- for (const RID &tracker : trackers) {
+ for (const RID &tracker : tracker_owner.get_owned_list()) {
tracker_check_profile(tracker, event->session);
}
@@ -2897,12 +2893,10 @@ XrPath OpenXRAPI::get_xr_path(const String &p_path) {
}
RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
- List<RID> current;
- tracker_owner.get_owned_list(¤t);
- for (const RID &E : current) {
- Tracker *tracker = tracker_owner.get_or_null(E);
+ for (const RID &tracker_rid : tracker_owner.get_owned_list()) {
+ Tracker *tracker = tracker_owner.get_or_null(tracker_rid);
if (tracker && tracker->toplevel_path == p_path) {
- return E;
+ return tracker_rid;
}
}
@@ -2910,12 +2904,10 @@ RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
}
RID OpenXRAPI::find_tracker(const String &p_name) {
- List<RID> current;
- tracker_owner.get_owned_list(¤t);
- for (const RID &E : current) {
- Tracker *tracker = tracker_owner.get_or_null(E);
+ for (const RID &tracker_rid : tracker_owner.get_owned_list()) {
+ Tracker *tracker = tracker_owner.get_or_null(tracker_rid);
if (tracker && tracker->name == p_name) {
- return E;
+ return tracker_rid;
}
}
@@ -3023,12 +3015,10 @@ RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_n
}
RID OpenXRAPI::find_action_set(const String p_name) {
- List<RID> current;
- action_set_owner.get_owned_list(¤t);
- for (const RID &E : current) {
- ActionSet *action_set = action_set_owner.get_or_null(E);
+ for (const RID &action_set_rid : action_set_owner.get_owned_list()) {
+ ActionSet *action_set = action_set_owner.get_or_null(action_set_rid);
if (action_set && action_set->name == p_name) {
- return E;
+ return action_set_rid;
}
}
@@ -3127,12 +3117,10 @@ void OpenXRAPI::action_set_free(RID p_action_set) {
}
RID OpenXRAPI::get_action_rid(XrAction p_action) {
- List<RID> current;
- action_owner.get_owned_list(¤t);
- for (const RID &E : current) {
- Action *action = action_owner.get_or_null(E);
+ for (const RID &action_rid : action_owner.get_owned_list()) {
+ Action *action = action_owner.get_or_null(action_rid);
if (action && action->handle == p_action) {
- return E;
+ return action_rid;
}
}
@@ -3140,12 +3128,10 @@ RID OpenXRAPI::get_action_rid(XrAction p_action) {
}
RID OpenXRAPI::find_action(const String &p_name, const RID &p_action_set) {
- List<RID> current;
- action_owner.get_owned_list(¤t);
- for (const RID &E : current) {
- Action *action = action_owner.get_or_null(E);
+ for (const RID &action_rid : action_owner.get_owned_list()) {
+ Action *action = action_owner.get_or_null(action_rid);
if (action && action->name == p_name && (p_action_set.is_null() || action->action_set_rid == p_action_set)) {
- return E;
+ return action_rid;
}
}
@@ -3257,12 +3243,10 @@ void OpenXRAPI::action_free(RID p_action) {
}
RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) {
- List<RID> current;
- interaction_profile_owner.get_owned_list(¤t);
- for (const RID &E : current) {
- InteractionProfile *ip = interaction_profile_owner.get_or_null(E);
+ for (const RID &ip_rid : interaction_profile_owner.get_owned_list()) {
+ InteractionProfile *ip = interaction_profile_owner.get_or_null(ip_rid);
if (ip && ip->path == p_path) {
- return E;
+ return ip_rid;
}
}
diff --git a/servers/rendering/renderer_canvas_cull.cpp b/servers/rendering/renderer_canvas_cull.cpp
index 03c347c32173..b7285e9d8e0f 100644
--- a/servers/rendering/renderer_canvas_cull.cpp
+++ b/servers/rendering/renderer_canvas_cull.cpp
@@ -2670,16 +2670,15 @@ bool RendererCanvasCull::free(RID p_rid) {
template <typename T>
void RendererCanvasCull::_free_rids(T &p_owner, const char *p_type) {
- List<RID> owned;
- p_owner.get_owned_list(&owned);
+ LocalVector<RID> owned = p_owner.get_owned_list();
if (owned.size()) {
if (owned.size() == 1) {
WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type));
} else {
WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type));
}
- for (const RID &E : owned) {
- free(E);
+ for (const RID &rid : owned) {
+ free(rid);
}
}
}
diff --git a/servers/rendering/renderer_rd/shader_rd.cpp b/servers/rendering/renderer_rd/shader_rd.cpp
index 8910876ffa19..7efe525df023 100644
--- a/servers/rendering/renderer_rd/shader_rd.cpp
+++ b/servers/rendering/renderer_rd/shader_rd.cpp
@@ -748,10 +748,8 @@ void ShaderRD::enable_group(int p_group) {
group_enabled.write[p_group] = true;
// Compile all versions again to include the new group.
- List<RID> all_versions;
- version_owner.get_owned_list(&all_versions);
- for (const RID &E : all_versions) {
- Version *version = version_owner.get_or_null(E);
+ for (const RID &version_rid : version_owner.get_owned_list()) {
+ Version *version = version_owner.get_or_null(version_rid);
version->mutex->lock();
_compile_version_start(version, p_group);
version->mutex->unlock();
@@ -907,13 +905,11 @@ bool ShaderRD::shader_cache_save_compressed_zstd = true;
bool ShaderRD::shader_cache_save_debug = true;
ShaderRD::~ShaderRD() {
- List<RID> remaining;
- version_owner.get_owned_list(&remaining);
+ LocalVector<RID> remaining = version_owner.get_owned_list();
if (remaining.size()) {
ERR_PRINT(itos(remaining.size()) + " shaders of type " + name + " were never freed");
- while (remaining.size()) {
- version_free(remaining.front()->get());
- remaining.pop_front();
+ for (const RID &version_rid : remaining) {
+ version_free(version_rid);
}
}
}
diff --git a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
index 613114b8a991..259de53a37bd 100644
--- a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
@@ -1640,10 +1640,7 @@ void TextureStorage::texture_set_detect_roughness_callback(RID p_texture, RS::Te
}
void TextureStorage::texture_debug_usage(List<RS::TextureInfo> *r_info) {
- List<RID> textures;
- texture_owner.get_owned_list(&textures);
-
- for (const RID &rid : textures) {
+ for (const RID &rid : texture_owner.get_owned_list()) {
Texture *t = texture_owner.get_or_null(rid);
if (!t) {
continue;
diff --git a/servers/rendering/rendering_device.cpp b/servers/rendering/rendering_device.cpp
index d02fd95c1ed6..18adea7ae94a 100644
--- a/servers/rendering/rendering_device.cpp
+++ b/servers/rendering/rendering_device.cpp
@@ -6946,21 +6946,20 @@ void RenderingDevice::_save_pipeline_cache(void *p_data) {
template <typename T>
void RenderingDevice::_free_rids(T &p_owner, const char *p_type) {
- List<RID> owned;
- p_owner.get_owned_list(&owned);
+ LocalVector<RID> owned = p_owner.get_owned_list();
if (owned.size()) {
if (owned.size() == 1) {
WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type));
} else {
WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type));
}
- for (const RID &E : owned) {
+ for (const RID &rid : owned) {
#ifdef DEV_ENABLED
- if (resource_names.has(E)) {
- print_line(String(" - ") + resource_names[E]);
+ if (resource_names.has(rid)) {
+ print_line(String(" - ") + resource_names[rid]);
}
#endif
- free(E);
+ free(rid);
}
}
}
@@ -7157,36 +7156,35 @@ void RenderingDevice::finalize() {
_free_rids(sampler_owner, "Sampler");
{
// For textures it's a bit more difficult because they may be shared.
- List<RID> owned;
- texture_owner.get_owned_list(&owned);
+ LocalVector<RID> owned = texture_owner.get_owned_list();
if (owned.size()) {
if (owned.size() == 1) {
WARN_PRINT("1 RID of type \"Texture\" was leaked.");
} else {
WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size()));
}
+ LocalVector<RID> owned_non_shared;
// Free shared first.
- for (List<RID>::Element *E = owned.front(); E;) {
- List<RID>::Element *N = E->next();
- if (texture_is_shared(E->get())) {
+ for (const RID &texture_rid : owned) {
+ if (texture_is_shared(texture_rid)) {
#ifdef DEV_ENABLED
- if (resource_names.has(E->get())) {
- print_line(String(" - ") + resource_names[E->get()]);
+ if (resource_names.has(texture_rid)) {
+ print_line(String(" - ") + resource_names[texture_rid]);
}
#endif
- free(E->get());
- owned.erase(E);
+ free(texture_rid);
+ } else {
+ owned_non_shared.push_back(texture_rid);
}
- E = N;
}
// Free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.
- for (const RID &E : owned) {
+ for (const RID &texture_rid : owned_non_shared) {
#ifdef DEV_ENABLED
- if (resource_names.has(E)) {
- print_line(String(" - ") + resource_names[E]);
+ if (resource_names.has(texture_rid)) {
+ print_line(String(" - ") + resource_names[texture_rid]);
}
#endif
- free(E);
+ free(texture_rid);
}
}
}
diff --git a/servers/rendering/storage/compositor_storage.cpp b/servers/rendering/storage/compositor_storage.cpp
index 102efbeea1d5..06b6b4cbca26 100644
--- a/servers/rendering/storage/compositor_storage.cpp
+++ b/servers/rendering/storage/compositor_storage.cpp
@@ -57,9 +57,7 @@ void RendererCompositorStorage::compositor_effect_free(RID p_rid) {
ERR_FAIL_NULL(effect);
// Remove this RID from any compositor that uses it.
- List<RID> compositor_rids;
- compositor_owner.get_owned_list(&compositor_rids);
- for (const RID &compositor_rid : compositor_rids) {
+ for (const RID &compositor_rid : compositor_owner.get_owned_list()) {
Compositor *compositor = compositor_owner.get_or_null(compositor_rid);
if (compositor) {
compositor->compositor_effects.erase(p_rid);
| diff --git a/core/templates/rid_owner.h b/core/templates/rid_owner.h
index 3ff34c407e4b..f87134092484 100644
--- a/core/templates/rid_owner.h
+++ b/core/templates/rid_owner.h
@@ -33,7 +33,7 @@
#include "core/os/memory.h"
#include "core/string/print_string.h"
-#include "core/templates/list.h"
+#include "core/templates/local_vector.h"
#include "core/templates/rid.h"
#include "core/templates/safe_refcount.h"
@@ -382,19 +382,21 @@ class RID_Alloc : public RID_AllocBase {
_FORCE_INLINE_ uint32_t get_rid_count() const {
return alloc_count;
- void get_owned_list(List<RID> *p_owned) const {
+ LocalVector<RID> owned;
mutex.lock();
for (size_t i = 0; i < max_alloc; i++) {
uint64_t validator = chunks[i / elements_in_chunk][i % elements_in_chunk].validator;
if (validator != 0xFFFFFFFF) {
+ owned.push_back(_make_from_id((validator << 32) | i));
mutex.unlock();
+ return owned;
//used for fast iteration in the elements or RIDs
@@ -506,8 +508,8 @@ class RID_PtrOwner {
@@ -562,8 +564,8 @@ class RID_Owner {
alloc.fill_owned_buffer(p_rid_buffer);
diff --git a/drivers/gles3/shader_gles3.cpp b/drivers/gles3/shader_gles3.cpp
index d7070d52f4aa..2411cd3025ed 100644
--- a/drivers/gles3/shader_gles3.cpp
+++ b/drivers/gles3/shader_gles3.cpp
@@ -841,13 +841,11 @@ bool ShaderGLES3::shader_cache_save_compressed_zstd = true;
bool ShaderGLES3::shader_cache_save_debug = true;
ShaderGLES3::~ShaderGLES3() {
+ for (RID &rid : remaining) {
+ version_free(rid);
diff --git a/drivers/gles3/storage/texture_storage.cpp b/drivers/gles3/storage/texture_storage.cpp
index b52b6a8f1984..7035a79d5e51 100644
--- a/drivers/gles3/storage/texture_storage.cpp
+++ b/drivers/gles3/storage/texture_storage.cpp
@@ -1470,10 +1470,7 @@ void TextureStorage::texture_set_detect_roughness_callback(RID p_texture, RS::Te
diff --git a/modules/navigation_2d/2d/godot_navigation_server_2d.cpp b/modules/navigation_2d/2d/godot_navigation_server_2d.cpp
index 2b4f898dafdf..048208f5e527 100644
--- a/modules/navigation_2d/2d/godot_navigation_server_2d.cpp
+++ b/modules/navigation_2d/2d/godot_navigation_server_2d.cpp
@@ -32,6 +32,7 @@
#include "scene/main/node.h"
#ifdef CLIPPER2_ENABLED
#include "nav_mesh_generator_2d.h"
@@ -193,11 +194,12 @@ void GodotNavigationServer2D::add_command(SetCommand2D *p_command) {
TypedArray<RID> GodotNavigationServer2D::get_maps() const {
diff --git a/modules/navigation_3d/3d/godot_navigation_server_3d.cpp b/modules/navigation_3d/3d/godot_navigation_server_3d.cpp
index 498566a04e79..d4469d3c3eac 100644
--- a/modules/navigation_3d/3d/godot_navigation_server_3d.cpp
+++ b/modules/navigation_3d/3d/godot_navigation_server_3d.cpp
@@ -94,11 +94,12 @@ void GodotNavigationServer3D::add_command(SetCommand3D *command) {
TypedArray<RID> GodotNavigationServer3D::get_maps() const {
diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cpp
index 4e0a0535c44a..befc3ebe2021 100644
--- a/modules/openxr/openxr_api.cpp
+++ b/modules/openxr/openxr_api.cpp
@@ -1415,9 +1415,7 @@ bool OpenXRAPI::on_state_synchronized() {
print_verbose("On state synchronized");
// Just in case, see if we already have active trackers...
- List<RID> trackers;
- tracker_owner.get_owned_list(&trackers);
- for (const RID &tracker : trackers) {
+ for (const RID &tracker : tracker_owner.get_owned_list()) {
tracker_check_profile(tracker);
@@ -2066,9 +2064,7 @@ bool OpenXRAPI::poll_events() {
XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent;
- List<RID> trackers;
- tracker_owner.get_owned_list(&trackers);
- for (const RID &tracker : trackers) {
+ for (const RID &tracker : tracker_owner.get_owned_list()) {
tracker_check_profile(tracker, event->session);
@@ -2897,12 +2893,10 @@ XrPath OpenXRAPI::get_xr_path(const String &p_path) {
RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
if (tracker && tracker->toplevel_path == p_path) {
@@ -2910,12 +2904,10 @@ RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
RID OpenXRAPI::find_tracker(const String &p_name) {
if (tracker && tracker->name == p_name) {
@@ -3023,12 +3015,10 @@ RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_n
RID OpenXRAPI::find_action_set(const String p_name) {
- action_set_owner.get_owned_list(¤t);
- ActionSet *action_set = action_set_owner.get_or_null(E);
+ for (const RID &action_set_rid : action_set_owner.get_owned_list()) {
+ ActionSet *action_set = action_set_owner.get_or_null(action_set_rid);
if (action_set && action_set->name == p_name) {
+ return action_set_rid;
@@ -3127,12 +3117,10 @@ void OpenXRAPI::action_set_free(RID p_action_set) {
RID OpenXRAPI::get_action_rid(XrAction p_action) {
if (action && action->handle == p_action) {
@@ -3140,12 +3128,10 @@ RID OpenXRAPI::get_action_rid(XrAction p_action) {
RID OpenXRAPI::find_action(const String &p_name, const RID &p_action_set) {
if (action && action->name == p_name && (p_action_set.is_null() || action->action_set_rid == p_action_set)) {
@@ -3257,12 +3243,10 @@ void OpenXRAPI::action_free(RID p_action) {
RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) {
- interaction_profile_owner.get_owned_list(¤t);
- InteractionProfile *ip = interaction_profile_owner.get_or_null(E);
+ for (const RID &ip_rid : interaction_profile_owner.get_owned_list()) {
+ InteractionProfile *ip = interaction_profile_owner.get_or_null(ip_rid);
if (ip && ip->path == p_path) {
+ return ip_rid;
diff --git a/servers/rendering/renderer_canvas_cull.cpp b/servers/rendering/renderer_canvas_cull.cpp
index 03c347c32173..b7285e9d8e0f 100644
--- a/servers/rendering/renderer_canvas_cull.cpp
+++ b/servers/rendering/renderer_canvas_cull.cpp
@@ -2670,16 +2670,15 @@ bool RendererCanvasCull::free(RID p_rid) {
void RendererCanvasCull::_free_rids(T &p_owner, const char *p_type) {
diff --git a/servers/rendering/renderer_rd/shader_rd.cpp b/servers/rendering/renderer_rd/shader_rd.cpp
index 8910876ffa19..7efe525df023 100644
--- a/servers/rendering/renderer_rd/shader_rd.cpp
+++ b/servers/rendering/renderer_rd/shader_rd.cpp
@@ -748,10 +748,8 @@ void ShaderRD::enable_group(int p_group) {
group_enabled.write[p_group] = true;
// Compile all versions again to include the new group.
- List<RID> all_versions;
- version_owner.get_owned_list(&all_versions);
- for (const RID &E : all_versions) {
+ for (const RID &version_rid : version_owner.get_owned_list()) {
+ Version *version = version_owner.get_or_null(version_rid);
version->mutex->lock();
_compile_version_start(version, p_group);
version->mutex->unlock();
@@ -907,13 +905,11 @@ bool ShaderRD::shader_cache_save_compressed_zstd = true;
bool ShaderRD::shader_cache_save_debug = true;
ShaderRD::~ShaderRD() {
+ for (const RID &version_rid : remaining) {
+ version_free(version_rid);
diff --git a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
index 613114b8a991..259de53a37bd 100644
--- a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
+++ b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp
@@ -1640,10 +1640,7 @@ void TextureStorage::texture_set_detect_roughness_callback(RID p_texture, RS::Te
diff --git a/servers/rendering/rendering_device.cpp b/servers/rendering/rendering_device.cpp
index d02fd95c1ed6..18adea7ae94a 100644
--- a/servers/rendering/rendering_device.cpp
+++ b/servers/rendering/rendering_device.cpp
@@ -6946,21 +6946,20 @@ void RenderingDevice::_save_pipeline_cache(void *p_data) {
void RenderingDevice::_free_rids(T &p_owner, const char *p_type) {
- if (resource_names.has(E)) {
- print_line(String(" - ") + resource_names[E]);
+ if (resource_names.has(rid)) {
+ print_line(String(" - ") + resource_names[rid]);
@@ -7157,36 +7156,35 @@ void RenderingDevice::finalize() {
_free_rids(sampler_owner, "Sampler");
{
// For textures it's a bit more difficult because they may be shared.
- List<RID> owned;
+ LocalVector<RID> owned = texture_owner.get_owned_list();
if (owned.size()) {
if (owned.size() == 1) {
WARN_PRINT("1 RID of type \"Texture\" was leaked.");
} else {
WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size()));
+ LocalVector<RID> owned_non_shared;
// Free shared first.
- for (List<RID>::Element *E = owned.front(); E;) {
- List<RID>::Element *N = E->next();
- if (texture_is_shared(E->get())) {
+ for (const RID &texture_rid : owned) {
+ if (texture_is_shared(texture_rid)) {
- if (resource_names.has(E->get())) {
- print_line(String(" - ") + resource_names[E->get()]);
+ if (resource_names.has(texture_rid)) {
+ print_line(String(" - ") + resource_names[texture_rid]);
}
- free(E->get());
- owned.erase(E);
+ free(texture_rid);
+ } else {
+ owned_non_shared.push_back(texture_rid);
- E = N;
// Free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.
- for (const RID &E : owned) {
+ for (const RID &texture_rid : owned_non_shared) {
- if (resource_names.has(E)) {
- print_line(String(" - ") + resource_names[E]);
+ if (resource_names.has(texture_rid)) {
+ print_line(String(" - ") + resource_names[texture_rid]);
+ free(texture_rid);
diff --git a/servers/rendering/storage/compositor_storage.cpp b/servers/rendering/storage/compositor_storage.cpp
index 102efbeea1d5..06b6b4cbca26 100644
--- a/servers/rendering/storage/compositor_storage.cpp
+++ b/servers/rendering/storage/compositor_storage.cpp
@@ -57,9 +57,7 @@ void RendererCompositorStorage::compositor_effect_free(RID p_rid) {
ERR_FAIL_NULL(effect);
// Remove this RID from any compositor that uses it.
- compositor_owner.get_owned_list(&compositor_rids);
- for (const RID &compositor_rid : compositor_rids) {
+ for (const RID &compositor_rid : compositor_owner.get_owned_list()) {
Compositor *compositor = compositor_owner.get_or_null(compositor_rid);
if (compositor) {
compositor->compositor_effects.erase(p_rid); | [
"+\tLocalVector<RID> get_owned_list() const {",
"-\t\t\t\tp_owned->push_back(_make_from_id((validator << 32) | i));",
"+#include <cstdint>",
"-\t\tVersion *version = version_owner.get_or_null(E);",
"-\t\ttexture_owner.get_owned_list(&owned);",
"-\t\t\t\tfree(E);",
"-\tList<RID> compositor_rids;"
] | [
18,
26,
104,
305,
380,
420,
433
] | {
"additions": 74,
"author": "YYF233333",
"deletions": 102,
"html_url": "https://github.com/godotengine/godot/pull/104738",
"issue_id": 104738,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 104738,
"repo": "godotengine/godot",
"title": "Use `LocalVector` in `RID_Owner::get_owned_list`",
"total_changes": 176
} |
735 | diff --git a/modules/openxr/editor/openxr_action_set_editor.cpp b/modules/openxr/editor/openxr_action_set_editor.cpp
index 06c5d48d159e..f205c8fc4b33 100644
--- a/modules/openxr/editor/openxr_action_set_editor.cpp
+++ b/modules/openxr/editor/openxr_action_set_editor.cpp
@@ -31,8 +31,14 @@
#include "openxr_action_set_editor.h"
#include "editor/editor_string_names.h"
+#include "editor/gui/editor_spin_slider.h"
#include "editor/themes/editor_scale.h"
#include "openxr_action_editor.h"
+#include "scene/gui/box_container.h"
+#include "scene/gui/button.h"
+#include "scene/gui/line_edit.h"
+#include "scene/gui/panel_container.h"
+#include "scene/gui/text_edit.h"
void OpenXRActionSetEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_do_set_name", "name"), &OpenXRActionSetEditor::_do_set_name);
@@ -127,8 +133,8 @@ void OpenXRActionSetEditor::_do_set_localized_name(const String p_new_text) {
action_set_localized_name->set_text(p_new_text);
}
-void OpenXRActionSetEditor::_on_action_set_priority_changed(const String p_new_text) {
- int64_t value = p_new_text.to_int();
+void OpenXRActionSetEditor::_on_action_set_priority_changed(const double p_new_value) {
+ int64_t value = (int64_t)p_new_value;
if (action_set->get_priority() != value) {
undo_redo->create_action(TTR("Change Action Sets priority"));
@@ -143,7 +149,7 @@ void OpenXRActionSetEditor::_on_action_set_priority_changed(const String p_new_t
void OpenXRActionSetEditor::_do_set_priority(int64_t p_value) {
action_set->set_priority(p_value);
- action_set_priority->set_text(itos(p_value));
+ action_set_priority->set_value_no_signal(p_value);
}
void OpenXRActionSetEditor::_on_add_action() {
@@ -260,11 +266,14 @@ OpenXRActionSetEditor::OpenXRActionSetEditor(Ref<OpenXRActionMap> p_action_map,
action_set_localized_name->set_accessibility_name(TTRC("Action Set Localized Name"));
action_set_hb->add_child(action_set_localized_name);
- action_set_priority = memnew(TextEdit);
- action_set_priority->set_text(itos(action_set->get_priority()));
+ action_set_priority = memnew(EditorSpinSlider);
action_set_priority->set_tooltip_text(TTR("Priority of the action set. If multiple action sets bind to the same input, the action set with the highest priority will be updated."));
- action_set_priority->set_custom_minimum_size(Size2(50.0 * EDSCALE, 0.0));
- action_set_priority->connect(SceneStringName(text_changed), callable_mp(this, &OpenXRActionSetEditor::_on_action_set_priority_changed));
+ action_set_priority->set_editing_integer(true);
+ action_set_priority->set_min(2147483647.0);
+ action_set_priority->set_min(-2147483648.0);
+ action_set_priority->set_value_no_signal(action_set->get_priority());
+ action_set_priority->set_custom_minimum_size(Size2(75.0 * EDSCALE, 0.0));
+ action_set_priority->connect(SceneStringName(value_changed), callable_mp(this, &OpenXRActionSetEditor::_on_action_set_priority_changed));
action_set_priority->set_accessibility_name(TTRC("Action Set Priority"));
action_set_hb->add_child(action_set_priority);
diff --git a/modules/openxr/editor/openxr_action_set_editor.h b/modules/openxr/editor/openxr_action_set_editor.h
index fc1beb943673..e7647a8586ee 100644
--- a/modules/openxr/editor/openxr_action_set_editor.h
+++ b/modules/openxr/editor/openxr_action_set_editor.h
@@ -34,11 +34,12 @@
#include "../action_map/openxr_action_set.h"
#include "openxr_action_editor.h"
-#include "scene/gui/box_container.h"
-#include "scene/gui/button.h"
-#include "scene/gui/line_edit.h"
-#include "scene/gui/panel_container.h"
-#include "scene/gui/text_edit.h"
+class EditorSpinSlider;
+class BoxContainer;
+class Button;
+class LineEdit;
+class PanelContainer;
+class TextEdit;
class OpenXRActionSetEditor : public HBoxContainer {
GDCLASS(OpenXRActionSetEditor, HBoxContainer);
@@ -56,7 +57,7 @@ class OpenXRActionSetEditor : public HBoxContainer {
HBoxContainer *action_set_hb = nullptr;
LineEdit *action_set_name = nullptr;
LineEdit *action_set_localized_name = nullptr;
- TextEdit *action_set_priority = nullptr;
+ EditorSpinSlider *action_set_priority = nullptr;
Button *add_action = nullptr;
Button *rem_action_set = nullptr;
VBoxContainer *actions_vb = nullptr;
@@ -68,7 +69,7 @@ class OpenXRActionSetEditor : public HBoxContainer {
void _on_toggle_expand();
void _on_action_set_name_changed(const String p_new_text);
void _on_action_set_localized_name_changed(const String p_new_text);
- void _on_action_set_priority_changed(const String p_new_text);
+ void _on_action_set_priority_changed(const double p_new_value);
void _on_add_action();
void _on_remove_action_set();
| diff --git a/modules/openxr/editor/openxr_action_set_editor.cpp b/modules/openxr/editor/openxr_action_set_editor.cpp
index 06c5d48d159e..f205c8fc4b33 100644
--- a/modules/openxr/editor/openxr_action_set_editor.cpp
+++ b/modules/openxr/editor/openxr_action_set_editor.cpp
@@ -31,8 +31,14 @@
#include "openxr_action_set_editor.h"
#include "editor/editor_string_names.h"
+#include "editor/gui/editor_spin_slider.h"
#include "editor/themes/editor_scale.h"
+#include "scene/gui/box_container.h"
+#include "scene/gui/button.h"
+#include "scene/gui/line_edit.h"
+#include "scene/gui/panel_container.h"
+#include "scene/gui/text_edit.h"
void OpenXRActionSetEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_do_set_name", "name"), &OpenXRActionSetEditor::_do_set_name);
@@ -127,8 +133,8 @@ void OpenXRActionSetEditor::_do_set_localized_name(const String p_new_text) {
action_set_localized_name->set_text(p_new_text);
-void OpenXRActionSetEditor::_on_action_set_priority_changed(const String p_new_text) {
- int64_t value = p_new_text.to_int();
+void OpenXRActionSetEditor::_on_action_set_priority_changed(const double p_new_value) {
+ int64_t value = (int64_t)p_new_value;
if (action_set->get_priority() != value) {
undo_redo->create_action(TTR("Change Action Sets priority"));
@@ -143,7 +149,7 @@ void OpenXRActionSetEditor::_on_action_set_priority_changed(const String p_new_t
void OpenXRActionSetEditor::_do_set_priority(int64_t p_value) {
action_set->set_priority(p_value);
- action_set_priority->set_text(itos(p_value));
+ action_set_priority->set_value_no_signal(p_value);
void OpenXRActionSetEditor::_on_add_action() {
@@ -260,11 +266,14 @@ OpenXRActionSetEditor::OpenXRActionSetEditor(Ref<OpenXRActionMap> p_action_map,
action_set_localized_name->set_accessibility_name(TTRC("Action Set Localized Name"));
action_set_hb->add_child(action_set_localized_name);
- action_set_priority->set_text(itos(action_set->get_priority()));
+ action_set_priority = memnew(EditorSpinSlider);
action_set_priority->set_tooltip_text(TTR("Priority of the action set. If multiple action sets bind to the same input, the action set with the highest priority will be updated."));
- action_set_priority->set_custom_minimum_size(Size2(50.0 * EDSCALE, 0.0));
- action_set_priority->connect(SceneStringName(text_changed), callable_mp(this, &OpenXRActionSetEditor::_on_action_set_priority_changed));
+ action_set_priority->set_editing_integer(true);
+ action_set_priority->set_min(2147483647.0);
+ action_set_priority->set_min(-2147483648.0);
+ action_set_priority->set_value_no_signal(action_set->get_priority());
+ action_set_priority->set_custom_minimum_size(Size2(75.0 * EDSCALE, 0.0));
+ action_set_priority->connect(SceneStringName(value_changed), callable_mp(this, &OpenXRActionSetEditor::_on_action_set_priority_changed));
action_set_priority->set_accessibility_name(TTRC("Action Set Priority"));
action_set_hb->add_child(action_set_priority);
diff --git a/modules/openxr/editor/openxr_action_set_editor.h b/modules/openxr/editor/openxr_action_set_editor.h
index fc1beb943673..e7647a8586ee 100644
--- a/modules/openxr/editor/openxr_action_set_editor.h
+++ b/modules/openxr/editor/openxr_action_set_editor.h
@@ -34,11 +34,12 @@
#include "../action_map/openxr_action_set.h"
-#include "scene/gui/box_container.h"
-#include "scene/gui/button.h"
-#include "scene/gui/panel_container.h"
-#include "scene/gui/text_edit.h"
+class EditorSpinSlider;
+class BoxContainer;
+class Button;
+class LineEdit;
+class PanelContainer;
+class TextEdit;
class OpenXRActionSetEditor : public HBoxContainer {
GDCLASS(OpenXRActionSetEditor, HBoxContainer);
@@ -56,7 +57,7 @@ class OpenXRActionSetEditor : public HBoxContainer {
HBoxContainer *action_set_hb = nullptr;
LineEdit *action_set_name = nullptr;
LineEdit *action_set_localized_name = nullptr;
- TextEdit *action_set_priority = nullptr;
+ EditorSpinSlider *action_set_priority = nullptr;
Button *add_action = nullptr;
Button *rem_action_set = nullptr;
VBoxContainer *actions_vb = nullptr;
@@ -68,7 +69,7 @@ class OpenXRActionSetEditor : public HBoxContainer {
void _on_toggle_expand();
void _on_action_set_name_changed(const String p_new_text);
void _on_action_set_localized_name_changed(const String p_new_text);
- void _on_action_set_priority_changed(const String p_new_text);
void _on_add_action();
void _on_remove_action_set(); | [
"-\taction_set_priority = memnew(TextEdit);",
"-#include \"scene/gui/line_edit.h\"",
"+\tvoid _on_action_set_priority_changed(const double p_new_value);"
] | [
43,
68,
94
] | {
"additions": 24,
"author": "lodetrick",
"deletions": 14,
"html_url": "https://github.com/godotengine/godot/pull/104461",
"issue_id": 104461,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 104461,
"repo": "godotengine/godot",
"title": "Editor: Replace TextEdit with EditorSpinSlider for XR Action Set Priority",
"total_changes": 38
} |
736 | diff --git a/SConstruct b/SConstruct
index 03990864310e..bcc2094f0541 100644
--- a/SConstruct
+++ b/SConstruct
@@ -296,6 +296,9 @@ opts.Add("asflags", "Custom flags for the assembler")
opts.Add("arflags", "Custom flags for the archive tool")
opts.Add("rcflags", "Custom flags for Windows resource compiler")
+opts.Add("c_compiler_launcher", "C compiler launcher (e.g. `ccache`)")
+opts.Add("cpp_compiler_launcher", "C++ compiler launcher (e.g. `ccache`)")
+
# Update the environment to have all above options defined
# in following code (especially platform and custom_modules).
opts.Update(env)
@@ -1122,6 +1125,13 @@ for key in (emitters := env.StaticObject.builder.emitter):
for key in (emitters := env.SharedObject.builder.emitter):
emitters[key] = ListEmitter([methods.redirect_emitter] + env.Flatten(emitters[key]))
+# Prepend compiler launchers
+if "c_compiler_launcher" in env:
+ env["CC"] = " ".join([env["c_compiler_launcher"], env["CC"]])
+
+if "cpp_compiler_launcher" in env:
+ env["CXX"] = " ".join([env["cpp_compiler_launcher"], env["CXX"]])
+
# Build subdirs, the build order is dependent on link order.
Export("env")
| diff --git a/SConstruct b/SConstruct
index 03990864310e..bcc2094f0541 100644
--- a/SConstruct
+++ b/SConstruct
@@ -296,6 +296,9 @@ opts.Add("asflags", "Custom flags for the assembler")
opts.Add("arflags", "Custom flags for the archive tool")
opts.Add("rcflags", "Custom flags for Windows resource compiler")
+opts.Add("c_compiler_launcher", "C compiler launcher (e.g. `ccache`)")
+opts.Add("cpp_compiler_launcher", "C++ compiler launcher (e.g. `ccache`)")
# Update the environment to have all above options defined
# in following code (especially platform and custom_modules).
opts.Update(env)
@@ -1122,6 +1125,13 @@ for key in (emitters := env.StaticObject.builder.emitter):
for key in (emitters := env.SharedObject.builder.emitter):
emitters[key] = ListEmitter([methods.redirect_emitter] + env.Flatten(emitters[key]))
+# Prepend compiler launchers
+if "c_compiler_launcher" in env:
+ env["CC"] = " ".join([env["c_compiler_launcher"], env["CC"]])
+if "cpp_compiler_launcher" in env:
+ env["CXX"] = " ".join([env["cpp_compiler_launcher"], env["CXX"]])
# Build subdirs, the build order is dependent on link order.
Export("env") | [] | [] | {
"additions": 10,
"author": "adamscott",
"deletions": 0,
"html_url": "https://github.com/godotengine/godot/pull/105498",
"issue_id": 105498,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 105498,
"repo": "godotengine/godot",
"title": "Add `{c,cpp}_compiler_launcher` options",
"total_changes": 10
} |
737 | diff --git a/.clang-format b/.clang-format
index 6a547cf6f118..87731d9eb833 100644
--- a/.clang-format
+++ b/.clang-format
@@ -52,8 +52,10 @@ AllowShortFunctionsOnASingleLine: Inline
# AlwaysBreakAfterReturnType: None
# AlwaysBreakBeforeMultilineStrings: false
# AlwaysBreakTemplateDeclarations: MultiLine
-# AttributeMacros:
-# - __capability
+AttributeMacros:
+ - _ALWAYS_INLINE_
+ - _FORCE_INLINE_
+ - _NO_INLINE_
# BinPackArguments: true
# BinPackParameters: true
# BitFieldColonSpacing: Both
diff --git a/drivers/metal/metal_objects.h b/drivers/metal/metal_objects.h
index 3966d2e8a472..1468ddc5a878 100644
--- a/drivers/metal/metal_objects.h
+++ b/drivers/metal/metal_objects.h
@@ -945,8 +945,7 @@ namespace rid {
// Converts an Objective-C object to a pointer, and incrementing the
// reference count.
-_FORCE_INLINE_
-void *owned(id p_id) {
+_FORCE_INLINE_ void *owned(id p_id) {
return (__bridge_retained void *)p_id;
}
@@ -962,14 +961,12 @@ MAKE_ID(MTLVertexDescriptor *, RDD::VertexFormatID)
MAKE_ID(id<MTLCommandQueue>, RDD::CommandPoolID)
// Converts a pointer to an Objective-C object without changing the reference count.
-_FORCE_INLINE_
-auto get(RDD::ID p_id) {
+_FORCE_INLINE_ auto get(RDD::ID p_id) {
return (p_id.id) ? (__bridge ::id)(void *)p_id.id : nil;
}
// Converts a pointer to an Objective-C object, and decrements the reference count.
-_FORCE_INLINE_
-auto release(RDD::ID p_id) {
+_FORCE_INLINE_ auto release(RDD::ID p_id) {
return (__bridge_transfer ::id)(void *)p_id.id;
}
diff --git a/misc/utility/clang_format_glsl.yml b/misc/utility/clang_format_glsl.yml
index a614e7d9ce20..1977bca2edb0 100644
--- a/misc/utility/clang_format_glsl.yml
+++ b/misc/utility/clang_format_glsl.yml
@@ -9,6 +9,10 @@ AlignTrailingComments:
OverEmptyLines: 0
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortFunctionsOnASingleLine: Inline
+AttributeMacros:
+ - _ALWAYS_INLINE_
+ - _FORCE_INLINE_
+ - _NO_INLINE_
BreakConstructorInitializers: AfterColon
ColumnLimit: 0
ConstructorInitializerIndentWidth: 8
diff --git a/tests/python_build/fixtures/gles3/vertex_fragment.glsl b/tests/python_build/fixtures/gles3/vertex_fragment.glsl
index 3004e22f25a0..90f33bbf82ee 100644
--- a/tests/python_build/fixtures/gles3/vertex_fragment.glsl
+++ b/tests/python_build/fixtures/gles3/vertex_fragment.glsl
@@ -3,7 +3,7 @@
#[modes]
mode_ninepatch = #define USE_NINEPATCH
-
+/* clang-format off */
#[specializations]
DISABLE_LIGHTING = false
@@ -12,13 +12,13 @@ DISABLE_LIGHTING = false
precision highp float;
precision highp int;
-
+/* clang-format on */
layout(location = 0) in highp vec3 vertex;
out highp vec4 position_interp;
void main() {
- position_interp = vec4(vertex.x,1,0,1);
+ position_interp = vec4(vertex.x, 1, 0, 1);
}
#[fragment]
diff --git a/tests/python_build/fixtures/glsl/compute.glsl b/tests/python_build/fixtures/glsl/compute.glsl
index e81f48d463d9..fbcb6c775f51 100644
--- a/tests/python_build/fixtures/glsl/compute.glsl
+++ b/tests/python_build/fixtures/glsl/compute.glsl
@@ -4,7 +4,6 @@
#VERSION_DEFINES
-
#include "_included.glsl"
void main() {
diff --git a/tests/python_build/fixtures/glsl/vertex_fragment.glsl b/tests/python_build/fixtures/glsl/vertex_fragment.glsl
index 0bdce783d753..90d5bd42afbf 100644
--- a/tests/python_build/fixtures/glsl/vertex_fragment.glsl
+++ b/tests/python_build/fixtures/glsl/vertex_fragment.glsl
@@ -11,9 +11,8 @@ lines = "#define MODE_LINES";
layout(location = 0) out vec3 uv_interp;
void main() {
-
#ifdef MODE_LINES
- uv_interp = vec3(0,0,1);
+ uv_interp = vec3(0, 0, 1);
#endif
}
@@ -28,5 +27,5 @@ void main() {
layout(location = 0) out vec4 dst_color;
void main() {
- dst_color = vec4(1,1,0,0);
+ dst_color = vec4(1, 1, 0, 0);
}
| diff --git a/.clang-format b/.clang-format
index 6a547cf6f118..87731d9eb833 100644
--- a/.clang-format
+++ b/.clang-format
@@ -52,8 +52,10 @@ AllowShortFunctionsOnASingleLine: Inline
# AlwaysBreakAfterReturnType: None
# AlwaysBreakBeforeMultilineStrings: false
# AlwaysBreakTemplateDeclarations: MultiLine
-# AttributeMacros:
-# - __capability
# BinPackArguments: true
# BinPackParameters: true
# BitFieldColonSpacing: Both
diff --git a/drivers/metal/metal_objects.h b/drivers/metal/metal_objects.h
index 3966d2e8a472..1468ddc5a878 100644
--- a/drivers/metal/metal_objects.h
+++ b/drivers/metal/metal_objects.h
@@ -945,8 +945,7 @@ namespace rid {
// Converts an Objective-C object to a pointer, and incrementing the
// reference count.
-void *owned(id p_id) {
return (__bridge_retained void *)p_id;
@@ -962,14 +961,12 @@ MAKE_ID(MTLVertexDescriptor *, RDD::VertexFormatID)
MAKE_ID(id<MTLCommandQueue>, RDD::CommandPoolID)
// Converts a pointer to an Objective-C object without changing the reference count.
-auto get(RDD::ID p_id) {
+_FORCE_INLINE_ auto get(RDD::ID p_id) {
return (p_id.id) ? (__bridge ::id)(void *)p_id.id : nil;
// Converts a pointer to an Objective-C object, and decrements the reference count.
-auto release(RDD::ID p_id) {
return (__bridge_transfer ::id)(void *)p_id.id;
diff --git a/misc/utility/clang_format_glsl.yml b/misc/utility/clang_format_glsl.yml
index a614e7d9ce20..1977bca2edb0 100644
--- a/misc/utility/clang_format_glsl.yml
+++ b/misc/utility/clang_format_glsl.yml
@@ -9,6 +9,10 @@ AlignTrailingComments:
OverEmptyLines: 0
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortFunctionsOnASingleLine: Inline
BreakConstructorInitializers: AfterColon
ColumnLimit: 0
ConstructorInitializerIndentWidth: 8
diff --git a/tests/python_build/fixtures/gles3/vertex_fragment.glsl b/tests/python_build/fixtures/gles3/vertex_fragment.glsl
index 3004e22f25a0..90f33bbf82ee 100644
--- a/tests/python_build/fixtures/gles3/vertex_fragment.glsl
+++ b/tests/python_build/fixtures/gles3/vertex_fragment.glsl
@@ -3,7 +3,7 @@
#[modes]
mode_ninepatch = #define USE_NINEPATCH
+/* clang-format off */
#[specializations]
DISABLE_LIGHTING = false
@@ -12,13 +12,13 @@ DISABLE_LIGHTING = false
precision highp float;
precision highp int;
+/* clang-format on */
layout(location = 0) in highp vec3 vertex;
out highp vec4 position_interp;
- position_interp = vec4(vertex.x,1,0,1);
+ position_interp = vec4(vertex.x, 1, 0, 1);
#[fragment]
diff --git a/tests/python_build/fixtures/glsl/compute.glsl b/tests/python_build/fixtures/glsl/compute.glsl
index e81f48d463d9..fbcb6c775f51 100644
--- a/tests/python_build/fixtures/glsl/compute.glsl
+++ b/tests/python_build/fixtures/glsl/compute.glsl
@@ -4,7 +4,6 @@
#VERSION_DEFINES
#include "_included.glsl"
diff --git a/tests/python_build/fixtures/glsl/vertex_fragment.glsl b/tests/python_build/fixtures/glsl/vertex_fragment.glsl
index 0bdce783d753..90d5bd42afbf 100644
--- a/tests/python_build/fixtures/glsl/vertex_fragment.glsl
+++ b/tests/python_build/fixtures/glsl/vertex_fragment.glsl
@@ -11,9 +11,8 @@ lines = "#define MODE_LINES";
layout(location = 0) out vec3 uv_interp;
#ifdef MODE_LINES
- uv_interp = vec3(0,0,1);
+ uv_interp = vec3(0, 0, 1);
#endif
@@ -28,5 +27,5 @@ void main() {
layout(location = 0) out vec4 dst_color;
- dst_color = vec4(1,1,0,0);
+ dst_color = vec4(1, 1, 0, 0); | [
"+_FORCE_INLINE_ void *owned(id p_id) {",
"+_FORCE_INLINE_ auto release(RDD::ID p_id) {"
] | [
27,
44
] | {
"additions": 16,
"author": "Repiteo",
"deletions": 15,
"html_url": "https://github.com/godotengine/godot/pull/105531",
"issue_id": 105531,
"merged_at": "2025-04-22T15:46:12Z",
"omission_probability": 0.1,
"pr_number": 105531,
"repo": "godotengine/godot",
"title": "Style: Declare inline macros as attributes",
"total_changes": 31
} |
738 | diff --git a/editor/gui/touch_actions_panel.cpp b/editor/gui/touch_actions_panel.cpp
index bc6576e519e9..5e6822adb192 100644
--- a/editor/gui/touch_actions_panel.cpp
+++ b/editor/gui/touch_actions_panel.cpp
@@ -45,6 +45,9 @@ void TouchActionsPanel::_notification(int p_what) {
DisplayServer::get_singleton()->set_hardware_keyboard_connection_change_callback(callable_mp(this, &TouchActionsPanel::_hardware_keyboard_connected));
_hardware_keyboard_connected(DisplayServer::get_singleton()->has_hardware_keyboard());
} break;
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ set_process_input(is_visible_in_tree());
+ } break;
case NOTIFICATION_THEME_CHANGED: {
drag_handle->set_texture(get_editor_theme_icon(SNAME("DragHandle")));
layout_toggle_button->set_button_icon(get_editor_theme_icon(SNAME("Orientation")));
@@ -53,10 +56,27 @@ void TouchActionsPanel::_notification(int p_what) {
delete_button->set_button_icon(get_editor_theme_icon(SNAME("Remove")));
undo_button->set_button_icon(get_editor_theme_icon(SNAME("UndoRedo")));
redo_button->set_button_icon(get_editor_theme_icon(SNAME("Redo")));
+ cut_button->set_button_icon(get_editor_theme_icon(SNAME("ActionCut")));
+ copy_button->set_button_icon(get_editor_theme_icon(SNAME("ActionCopy")));
+ paste_button->set_button_icon(get_editor_theme_icon(SNAME("ActionPaste")));
} break;
}
}
+void TouchActionsPanel::input(const Ref<InputEvent> &event) {
+ if (ctrl_btn_pressed) {
+ event->call(SNAME("set_ctrl_pressed"), true);
+ }
+
+ if (shift_btn_pressed) {
+ event->call(SNAME("set_shift_pressed"), true);
+ }
+
+ if (alt_btn_pressed) {
+ event->call(SNAME("set_alt_pressed"), true);
+ }
+}
+
void TouchActionsPanel::_hardware_keyboard_connected(bool p_connected) {
set_visible(!p_connected);
}
@@ -81,12 +101,26 @@ void TouchActionsPanel::_simulate_key_press(Key p_keycode) {
Input::get_singleton()->parse_input_event(event);
}
+void TouchActionsPanel::_on_modifier_button_toggled(bool p_pressed, int p_modifier) {
+ switch ((Modifier)p_modifier) {
+ case MODIFIER_CTRL:
+ ctrl_btn_pressed = p_pressed;
+ break;
+ case MODIFIER_SHIFT:
+ shift_btn_pressed = p_pressed;
+ break;
+ case MODIFIER_ALT:
+ alt_btn_pressed = p_pressed;
+ break;
+ }
+}
+
Button *TouchActionsPanel::_add_new_action_button(const String &p_shortcut, const String &p_name, Key p_keycode) {
Button *action_button = memnew(Button);
- action_button->set_focus_mode(Control::FOCUS_NONE);
- action_button->set_h_size_flags(Control::SIZE_SHRINK_CENTER);
- action_button->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
+ action_button->set_theme_type_variation("FlatMenuButton");
action_button->set_accessibility_name(p_name);
+ action_button->set_focus_mode(FOCUS_NONE);
+ action_button->set_icon_alignment(HORIZONTAL_ALIGNMENT_CENTER);
if (p_keycode == Key::NONE) {
action_button->connect(SceneStringName(pressed), callable_mp(this, &TouchActionsPanel::_simulate_editor_shortcut).bind(p_shortcut));
} else {
@@ -96,6 +130,29 @@ Button *TouchActionsPanel::_add_new_action_button(const String &p_shortcut, cons
return action_button;
}
+void TouchActionsPanel::_add_new_modifier_button(Modifier p_modifier) {
+ String text;
+ switch (p_modifier) {
+ case MODIFIER_CTRL:
+ text = "Ctrl";
+ break;
+ case MODIFIER_SHIFT:
+ text = "Shift";
+ break;
+ case MODIFIER_ALT:
+ text = "Alt";
+ break;
+ }
+ Button *toggle_button = memnew(Button);
+ toggle_button->set_text(text);
+ toggle_button->set_toggle_mode(true);
+ toggle_button->set_theme_type_variation("FlatMenuButton");
+ toggle_button->set_accessibility_name(text);
+ toggle_button->set_focus_mode(FOCUS_NONE);
+ toggle_button->connect(SceneStringName(toggled), callable_mp(this, &TouchActionsPanel::_on_modifier_button_toggled).bind((int)p_modifier));
+ box->add_child(toggle_button);
+}
+
void TouchActionsPanel::_on_drag_handle_gui_input(const Ref<InputEvent> &p_event) {
if (lock_panel_position) {
return;
@@ -106,7 +163,11 @@ void TouchActionsPanel::_on_drag_handle_gui_input(const Ref<InputEvent> &p_event
dragging = true;
drag_offset = mouse_button_event->get_position();
} else {
- dragging = false;
+ if (dragging) {
+ dragging = false;
+ EditorSettings::get_singleton()->set("_touch_actions_panel_position", get_position());
+ EditorSettings::get_singleton()->save();
+ }
}
}
@@ -124,6 +185,9 @@ void TouchActionsPanel::_on_drag_handle_gui_input(const Ref<InputEvent> &p_event
void TouchActionsPanel::_switch_layout() {
box->set_vertical(!box->is_vertical());
reset_size();
+ queue_redraw();
+ EditorSettings::get_singleton()->set("_touch_actions_panel_vertical_layout", box->is_vertical());
+ EditorSettings::get_singleton()->save();
}
void TouchActionsPanel::_lock_panel_toggled(bool p_pressed) {
@@ -141,11 +205,12 @@ TouchActionsPanel::TouchActionsPanel() {
panel_style->set_content_margin_all(12);
add_theme_style_override(SceneStringName(panel), panel_style);
- set_anchors_and_offsets_preset(Control::PRESET_CENTER_BOTTOM, Control::PRESET_MODE_MINSIZE, 80);
+ set_position(EDITOR_DEF("_touch_actions_panel_position", Point2(480, 480))); // Dropped it here for no good reason — users can move it anyway.
box = memnew(BoxContainer);
box->set_alignment(BoxContainer::ALIGNMENT_CENTER);
- box->add_theme_constant_override("separation", 15);
+ box->add_theme_constant_override("separation", 20);
+ box->set_vertical(EDITOR_DEF("_touch_actions_panel_vertical_layout", false));
add_child(box);
drag_handle = memnew(TextureRect);
@@ -155,19 +220,19 @@ TouchActionsPanel::TouchActionsPanel() {
box->add_child(drag_handle);
layout_toggle_button = memnew(Button);
+ layout_toggle_button->set_theme_type_variation("FlatMenuButton");
layout_toggle_button->set_accessibility_name(TTRC("Switch Layout"));
- layout_toggle_button->set_focus_mode(Control::FOCUS_NONE);
- layout_toggle_button->set_h_size_flags(Control::SIZE_SHRINK_CENTER);
- layout_toggle_button->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
+ layout_toggle_button->set_focus_mode(FOCUS_NONE);
+ layout_toggle_button->set_icon_alignment(HORIZONTAL_ALIGNMENT_CENTER);
layout_toggle_button->connect(SceneStringName(pressed), callable_mp(this, &TouchActionsPanel::_switch_layout));
box->add_child(layout_toggle_button);
lock_panel_button = memnew(Button);
lock_panel_button->set_toggle_mode(true);
+ lock_panel_button->set_theme_type_variation("FlatMenuButton");
lock_panel_button->set_accessibility_name(TTRC("Lock Panel"));
- lock_panel_button->set_focus_mode(Control::FOCUS_NONE);
- lock_panel_button->set_h_size_flags(Control::SIZE_SHRINK_CENTER);
- lock_panel_button->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
+ lock_panel_button->set_focus_mode(FOCUS_NONE);
+ lock_panel_button->set_icon_alignment(HORIZONTAL_ALIGNMENT_CENTER);
lock_panel_button->connect(SceneStringName(toggled), callable_mp(this, &TouchActionsPanel::_lock_panel_toggled));
box->add_child(lock_panel_button);
@@ -177,8 +242,15 @@ TouchActionsPanel::TouchActionsPanel() {
box->add_child(separator);
// Add action buttons.
- save_button = _add_new_action_button("editor/save_scene", TTR("Save"));
- delete_button = _add_new_action_button("", TTR("Delete"), Key::KEY_DELETE);
- undo_button = _add_new_action_button("ui_undo", TTR("Undo"));
- redo_button = _add_new_action_button("ui_redo", TTR("Redo"));
+ save_button = _add_new_action_button("editor/save_scene", TTRC("Save"));
+ delete_button = _add_new_action_button("", TTRC("Delete"), Key::KEY_DELETE);
+ undo_button = _add_new_action_button("ui_undo", TTRC("Undo"));
+ redo_button = _add_new_action_button("ui_redo", TTRC("Redo"));
+ cut_button = _add_new_action_button("ui_cut", TTRC("Cut"));
+ copy_button = _add_new_action_button("ui_copy", TTRC("Copy"));
+ paste_button = _add_new_action_button("ui_paste", TTRC("Paste"));
+
+ _add_new_modifier_button(MODIFIER_CTRL);
+ _add_new_modifier_button(MODIFIER_SHIFT);
+ _add_new_modifier_button(MODIFIER_ALT);
}
diff --git a/editor/gui/touch_actions_panel.h b/editor/gui/touch_actions_panel.h
index 8fde9f8af552..f8eae906d15f 100644
--- a/editor/gui/touch_actions_panel.h
+++ b/editor/gui/touch_actions_panel.h
@@ -45,6 +45,9 @@ class TouchActionsPanel : public PanelContainer {
Button *delete_button = nullptr;
Button *undo_button = nullptr;
Button *redo_button = nullptr;
+ Button *cut_button = nullptr;
+ Button *copy_button = nullptr;
+ Button *paste_button = nullptr;
TextureRect *drag_handle = nullptr;
Button *layout_toggle_button = nullptr;
@@ -54,7 +57,18 @@ class TouchActionsPanel : public PanelContainer {
bool dragging = false;
Vector2 drag_offset;
+ enum Modifier {
+ MODIFIER_CTRL,
+ MODIFIER_SHIFT,
+ MODIFIER_ALT
+ };
+
+ bool ctrl_btn_pressed = false;
+ bool shift_btn_pressed = false;
+ bool alt_btn_pressed = false;
+
void _notification(int p_what);
+ virtual void input(const Ref<InputEvent> &event) override;
void _simulate_editor_shortcut(const String &p_shortcut_name);
void _simulate_key_press(Key p_keycode);
@@ -63,6 +77,9 @@ class TouchActionsPanel : public PanelContainer {
void _lock_panel_toggled(bool p_pressed);
Button *_add_new_action_button(const String &p_shortcut, const String &p_name, Key p_keycode = Key::NONE);
+ void _add_new_modifier_button(Modifier p_modifier);
+ void _on_modifier_button_toggled(bool p_pressed, int p_modifier);
+
void _hardware_keyboard_connected(bool p_connected);
public:
| diff --git a/editor/gui/touch_actions_panel.cpp b/editor/gui/touch_actions_panel.cpp
index bc6576e519e9..5e6822adb192 100644
--- a/editor/gui/touch_actions_panel.cpp
+++ b/editor/gui/touch_actions_panel.cpp
@@ -45,6 +45,9 @@ void TouchActionsPanel::_notification(int p_what) {
DisplayServer::get_singleton()->set_hardware_keyboard_connection_change_callback(callable_mp(this, &TouchActionsPanel::_hardware_keyboard_connected));
_hardware_keyboard_connected(DisplayServer::get_singleton()->has_hardware_keyboard());
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ set_process_input(is_visible_in_tree());
+ } break;
case NOTIFICATION_THEME_CHANGED: {
drag_handle->set_texture(get_editor_theme_icon(SNAME("DragHandle")));
layout_toggle_button->set_button_icon(get_editor_theme_icon(SNAME("Orientation")));
@@ -53,10 +56,27 @@ void TouchActionsPanel::_notification(int p_what) {
delete_button->set_button_icon(get_editor_theme_icon(SNAME("Remove")));
undo_button->set_button_icon(get_editor_theme_icon(SNAME("UndoRedo")));
redo_button->set_button_icon(get_editor_theme_icon(SNAME("Redo")));
+ cut_button->set_button_icon(get_editor_theme_icon(SNAME("ActionCut")));
+ copy_button->set_button_icon(get_editor_theme_icon(SNAME("ActionCopy")));
+ paste_button->set_button_icon(get_editor_theme_icon(SNAME("ActionPaste")));
+void TouchActionsPanel::input(const Ref<InputEvent> &event) {
+ if (ctrl_btn_pressed) {
+ event->call(SNAME("set_ctrl_pressed"), true);
+ if (shift_btn_pressed) {
+ event->call(SNAME("set_shift_pressed"), true);
+ if (alt_btn_pressed) {
+ event->call(SNAME("set_alt_pressed"), true);
void TouchActionsPanel::_hardware_keyboard_connected(bool p_connected) {
set_visible(!p_connected);
@@ -81,12 +101,26 @@ void TouchActionsPanel::_simulate_key_press(Key p_keycode) {
Input::get_singleton()->parse_input_event(event);
+void TouchActionsPanel::_on_modifier_button_toggled(bool p_pressed, int p_modifier) {
+ switch ((Modifier)p_modifier) {
+ ctrl_btn_pressed = p_pressed;
+ shift_btn_pressed = p_pressed;
+ alt_btn_pressed = p_pressed;
Button *TouchActionsPanel::_add_new_action_button(const String &p_shortcut, const String &p_name, Key p_keycode) {
Button *action_button = memnew(Button);
- action_button->set_focus_mode(Control::FOCUS_NONE);
- action_button->set_h_size_flags(Control::SIZE_SHRINK_CENTER);
- action_button->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
+ action_button->set_theme_type_variation("FlatMenuButton");
action_button->set_accessibility_name(p_name);
+ action_button->set_focus_mode(FOCUS_NONE);
+ action_button->set_icon_alignment(HORIZONTAL_ALIGNMENT_CENTER);
if (p_keycode == Key::NONE) {
action_button->connect(SceneStringName(pressed), callable_mp(this, &TouchActionsPanel::_simulate_editor_shortcut).bind(p_shortcut));
} else {
@@ -96,6 +130,29 @@ Button *TouchActionsPanel::_add_new_action_button(const String &p_shortcut, cons
return action_button;
+void TouchActionsPanel::_add_new_modifier_button(Modifier p_modifier) {
+ String text;
+ switch (p_modifier) {
+ text = "Ctrl";
+ text = "Shift";
+ text = "Alt";
+ Button *toggle_button = memnew(Button);
+ toggle_button->set_text(text);
+ toggle_button->set_toggle_mode(true);
+ toggle_button->set_theme_type_variation("FlatMenuButton");
+ toggle_button->set_accessibility_name(text);
+ toggle_button->set_focus_mode(FOCUS_NONE);
+ box->add_child(toggle_button);
void TouchActionsPanel::_on_drag_handle_gui_input(const Ref<InputEvent> &p_event) {
if (lock_panel_position) {
return;
@@ -106,7 +163,11 @@ void TouchActionsPanel::_on_drag_handle_gui_input(const Ref<InputEvent> &p_event
dragging = true;
drag_offset = mouse_button_event->get_position();
} else {
- dragging = false;
+ if (dragging) {
+ dragging = false;
+ EditorSettings::get_singleton()->set("_touch_actions_panel_position", get_position());
+ EditorSettings::get_singleton()->save();
}
@@ -124,6 +185,9 @@ void TouchActionsPanel::_on_drag_handle_gui_input(const Ref<InputEvent> &p_event
void TouchActionsPanel::_switch_layout() {
box->set_vertical(!box->is_vertical());
reset_size();
+ EditorSettings::get_singleton()->set("_touch_actions_panel_vertical_layout", box->is_vertical());
+ EditorSettings::get_singleton()->save();
void TouchActionsPanel::_lock_panel_toggled(bool p_pressed) {
@@ -141,11 +205,12 @@ TouchActionsPanel::TouchActionsPanel() {
panel_style->set_content_margin_all(12);
add_theme_style_override(SceneStringName(panel), panel_style);
- set_anchors_and_offsets_preset(Control::PRESET_CENTER_BOTTOM, Control::PRESET_MODE_MINSIZE, 80);
+ set_position(EDITOR_DEF("_touch_actions_panel_position", Point2(480, 480))); // Dropped it here for no good reason — users can move it anyway.
box = memnew(BoxContainer);
box->set_alignment(BoxContainer::ALIGNMENT_CENTER);
- box->add_theme_constant_override("separation", 15);
+ box->add_theme_constant_override("separation", 20);
+ box->set_vertical(EDITOR_DEF("_touch_actions_panel_vertical_layout", false));
add_child(box);
drag_handle = memnew(TextureRect);
@@ -155,19 +220,19 @@ TouchActionsPanel::TouchActionsPanel() {
box->add_child(drag_handle);
layout_toggle_button = memnew(Button);
+ layout_toggle_button->set_theme_type_variation("FlatMenuButton");
layout_toggle_button->set_accessibility_name(TTRC("Switch Layout"));
- layout_toggle_button->set_focus_mode(Control::FOCUS_NONE);
- layout_toggle_button->set_h_size_flags(Control::SIZE_SHRINK_CENTER);
- layout_toggle_button->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
+ layout_toggle_button->set_focus_mode(FOCUS_NONE);
+ layout_toggle_button->set_icon_alignment(HORIZONTAL_ALIGNMENT_CENTER);
layout_toggle_button->connect(SceneStringName(pressed), callable_mp(this, &TouchActionsPanel::_switch_layout));
box->add_child(layout_toggle_button);
lock_panel_button = memnew(Button);
lock_panel_button->set_toggle_mode(true);
+ lock_panel_button->set_theme_type_variation("FlatMenuButton");
lock_panel_button->set_accessibility_name(TTRC("Lock Panel"));
- lock_panel_button->set_h_size_flags(Control::SIZE_SHRINK_CENTER);
- lock_panel_button->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
+ lock_panel_button->set_focus_mode(FOCUS_NONE);
lock_panel_button->connect(SceneStringName(toggled), callable_mp(this, &TouchActionsPanel::_lock_panel_toggled));
box->add_child(lock_panel_button);
@@ -177,8 +242,15 @@ TouchActionsPanel::TouchActionsPanel() {
box->add_child(separator);
// Add action buttons.
- save_button = _add_new_action_button("editor/save_scene", TTR("Save"));
- delete_button = _add_new_action_button("", TTR("Delete"), Key::KEY_DELETE);
- undo_button = _add_new_action_button("ui_undo", TTR("Undo"));
- redo_button = _add_new_action_button("ui_redo", TTR("Redo"));
+ save_button = _add_new_action_button("editor/save_scene", TTRC("Save"));
+ delete_button = _add_new_action_button("", TTRC("Delete"), Key::KEY_DELETE);
+ undo_button = _add_new_action_button("ui_undo", TTRC("Undo"));
+ redo_button = _add_new_action_button("ui_redo", TTRC("Redo"));
+ cut_button = _add_new_action_button("ui_cut", TTRC("Cut"));
+ copy_button = _add_new_action_button("ui_copy", TTRC("Copy"));
+ paste_button = _add_new_action_button("ui_paste", TTRC("Paste"));
+ _add_new_modifier_button(MODIFIER_CTRL);
+ _add_new_modifier_button(MODIFIER_ALT);
diff --git a/editor/gui/touch_actions_panel.h b/editor/gui/touch_actions_panel.h
index 8fde9f8af552..f8eae906d15f 100644
--- a/editor/gui/touch_actions_panel.h
+++ b/editor/gui/touch_actions_panel.h
@@ -45,6 +45,9 @@ class TouchActionsPanel : public PanelContainer {
Button *delete_button = nullptr;
Button *undo_button = nullptr;
Button *redo_button = nullptr;
+ Button *copy_button = nullptr;
+ Button *paste_button = nullptr;
TextureRect *drag_handle = nullptr;
Button *layout_toggle_button = nullptr;
@@ -54,7 +57,18 @@ class TouchActionsPanel : public PanelContainer {
bool dragging = false;
Vector2 drag_offset;
+ enum Modifier {
+ MODIFIER_SHIFT,
+ MODIFIER_ALT
+ };
+ bool ctrl_btn_pressed = false;
+ bool shift_btn_pressed = false;
+ bool alt_btn_pressed = false;
void _notification(int p_what);
+ virtual void input(const Ref<InputEvent> &event) override;
void _simulate_editor_shortcut(const String &p_shortcut_name);
void _simulate_key_press(Key p_keycode);
@@ -63,6 +77,9 @@ class TouchActionsPanel : public PanelContainer {
void _lock_panel_toggled(bool p_pressed);
Button *_add_new_action_button(const String &p_shortcut, const String &p_name, Key p_keycode = Key::NONE);
+ void _on_modifier_button_toggled(bool p_pressed, int p_modifier);
void _hardware_keyboard_connected(bool p_connected);
public: | [
"+\ttoggle_button->connect(SceneStringName(toggled), callable_mp(this, &TouchActionsPanel::_on_modifier_button_toggled).bind((int)p_modifier));",
"+\t\t\t}",
"+\tqueue_redraw();",
"-\tlock_panel_button->set_focus_mode(Control::FOCUS_NONE);",
"+\tlock_panel_button->set_icon_alignment(HORIZONTAL_ALIGNMENT_CENTER);",
"+\t_add_new_modifier_button(MODIFIER_SHIFT);",
"+\tButton *cut_button = nullptr;",
"+\t\tMODIFIER_CTRL,",
"+\tvoid _add_new_modifier_button(Modifier p_modifier);"
] | [
95,
111,
119,
158,
162,
183,
194,
205,
223
] | {
"additions": 105,
"author": "syntaxerror247",
"deletions": 16,
"html_url": "https://github.com/godotengine/godot/pull/105140",
"issue_id": 105140,
"merged_at": "2025-04-15T17:33:20Z",
"omission_probability": 0.1,
"pr_number": 105140,
"repo": "godotengine/godot",
"title": "Android Editor: Add new actions and enhancements to `TouchActionsPanel`",
"total_changes": 121
} |
739 | diff --git a/ext/random/random.stub.php b/ext/random/random.stub.php
index fc3b178e55fff..b59221bf9180f 100644
--- a/ext/random/random.stub.php
+++ b/ext/random/random.stub.php
@@ -27,9 +27,13 @@ function rand(int $min = UNKNOWN, int $max = UNKNOWN): int {}
function mt_rand(int $min = UNKNOWN, int $max = UNKNOWN): int {}
+ /** @compile-time-eval */
function mt_getrandmax(): int {}
- /** @alias mt_getrandmax */
+ /**
+ * @compile-time-eval
+ * @alias mt_getrandmax
+ */
function getrandmax(): int {}
/** @refcount 1 */
diff --git a/ext/random/random_arginfo.h b/ext/random/random_arginfo.h
index 3b06d7ba9e4f3..c1cfb8eb34132 100644
--- a/ext/random/random_arginfo.h
+++ b/ext/random/random_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: fad14b8b8abaf9f33d7837ba8f6190c5d10ff63f */
+ * Stub hash: 8b30f08404f2912d40f4cb61b76ec283af19b79c */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_lcg_value, 0, 0, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
@@ -160,8 +160,8 @@ static const zend_function_entry ext_functions[] = {
ZEND_RAW_FENTRY("srand", zif_mt_srand, arginfo_srand, 0, NULL, NULL)
ZEND_FE(rand, arginfo_rand)
ZEND_FE(mt_rand, arginfo_mt_rand)
- ZEND_FE(mt_getrandmax, arginfo_mt_getrandmax)
- ZEND_RAW_FENTRY("getrandmax", zif_mt_getrandmax, arginfo_getrandmax, 0, NULL, NULL)
+ ZEND_RAW_FENTRY("mt_getrandmax", zif_mt_getrandmax, arginfo_mt_getrandmax, ZEND_ACC_COMPILE_TIME_EVAL, NULL, NULL)
+ ZEND_RAW_FENTRY("getrandmax", zif_mt_getrandmax, arginfo_getrandmax, ZEND_ACC_COMPILE_TIME_EVAL, NULL, NULL)
ZEND_FE(random_bytes, arginfo_random_bytes)
ZEND_FE(random_int, arginfo_random_int)
ZEND_FE_END
| diff --git a/ext/random/random.stub.php b/ext/random/random.stub.php
index fc3b178e55fff..b59221bf9180f 100644
--- a/ext/random/random.stub.php
+++ b/ext/random/random.stub.php
@@ -27,9 +27,13 @@ function rand(int $min = UNKNOWN, int $max = UNKNOWN): int {}
function mt_rand(int $min = UNKNOWN, int $max = UNKNOWN): int {}
+ /** @compile-time-eval */
function mt_getrandmax(): int {}
- /** @alias mt_getrandmax */
+ /**
+ * @compile-time-eval
+ * @alias mt_getrandmax
+ */
function getrandmax(): int {}
/** @refcount 1 */
diff --git a/ext/random/random_arginfo.h b/ext/random/random_arginfo.h
index 3b06d7ba9e4f3..c1cfb8eb34132 100644
--- a/ext/random/random_arginfo.h
+++ b/ext/random/random_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: fad14b8b8abaf9f33d7837ba8f6190c5d10ff63f */
+ * Stub hash: 8b30f08404f2912d40f4cb61b76ec283af19b79c */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_lcg_value, 0, 0, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
@@ -160,8 +160,8 @@ static const zend_function_entry ext_functions[] = {
ZEND_RAW_FENTRY("srand", zif_mt_srand, arginfo_srand, 0, NULL, NULL)
ZEND_FE(rand, arginfo_rand)
ZEND_FE(mt_rand, arginfo_mt_rand)
- ZEND_FE(mt_getrandmax, arginfo_mt_getrandmax)
- ZEND_RAW_FENTRY("getrandmax", zif_mt_getrandmax, arginfo_getrandmax, 0, NULL, NULL)
+ ZEND_RAW_FENTRY("mt_getrandmax", zif_mt_getrandmax, arginfo_mt_getrandmax, ZEND_ACC_COMPILE_TIME_EVAL, NULL, NULL)
+ ZEND_RAW_FENTRY("getrandmax", zif_mt_getrandmax, arginfo_getrandmax, ZEND_ACC_COMPILE_TIME_EVAL, NULL, NULL)
ZEND_FE(random_bytes, arginfo_random_bytes)
ZEND_FE(random_int, arginfo_random_int)
ZEND_FE_END | [] | [] | {
"additions": 8,
"author": "TimWolla",
"deletions": 4,
"html_url": "https://github.com/php/php-src/pull/18425",
"issue_id": 18425,
"merged_at": "2025-04-25T20:57:04Z",
"omission_probability": 0.1,
"pr_number": 18425,
"repo": "php/php-src",
"title": "random: Mark `mt_getrandmax()` as `@compile-time-eval`",
"total_changes": 12
} |
740 | diff --git a/docs/release-process.md b/docs/release-process.md
index 36963b4318ead..cbfa791db6ef5 100644
--- a/docs/release-process.md
+++ b/docs/release-process.md
@@ -73,7 +73,7 @@ releases.
> When you are unsure about anything, ask a previous RM before proceeding.
> Ideally, make sure a previous RM is available to answer questions during
> the first few releases of your version. For the steps related to the
- > `web-php`, `web-qa`, and `web-php-distributions` repositories, try to have
+ > `web-php` and `web-php-distributions` repositories, try to have
> someone from the webmaster team on hand.
5. Verify the tags to be extra sure everything was tagged properly.
@@ -325,7 +325,7 @@ slightly different steps. We'll call attention where the steps differ.
downloads.php.net.
```shell
- scp php-X.Y.ZRCn.tar.* downloads.php.net:~/public_html/
+ scp php-X.Y.ZRCn.tar.* downloads.internal.php.net:~/public_html/
```
> 💬 **Hint** \
@@ -359,11 +359,10 @@ slightly different steps. We'll call attention where the steps differ.
## Announcing a non-stable release (alpha/beta/RC)
-1. Switch to your local clone of the `web-qa` repository and update the
+1. Switch to your local clone of the `web-php` repository and update the
information in the `$QA_RELEASES` array in `include/release-qa.php`.
Follow the documentation in the file for editing the QA release information.
- See also [Announce 8.1.0RC3][] and [8.1.6RC1][] for examples.
Add, commit, and push your changes, when finished.
@@ -716,20 +715,7 @@ slightly different steps. We'll call attention where the steps differ.
```shell
./bin/news2html 'https://github.com/php/php-src/raw/php-X.Y.Z/NEWS' 'X.Y.Z' 'ChangeLog-X.php'
```
-
-9. Review all the changes in `web-php`, commit, and push them.
-
- ```shell
- git add -p
- git add archive/entries/*.xml releases/*.php
- git commit --gpg-sign=YOURKEYID -m "Announce PHP X.Y.Z"
- git push upstream master
- ```
-
- See [Announce PHP 8.1.6][] for an example commit.
-
-10. Switch to your local clone of the `web-qa` repository and update the
- information in the `$QA_RELEASES` array in `include/release-qa.php`.
+8. Update the information in the `$QA_RELEASES` array in `include/release-qa.php`.
The array probably contains information about the RC released two weeks ago
in preparation for the current release. Since the current release is now GA,
@@ -737,18 +723,20 @@ slightly different steps. We'll call attention where the steps differ.
It is sufficient to set the `number` property for the release to `0` to
stop displaying the RC build on the QA website. You may also remove the
- sha256 hashes for the RC tarballs, but it's not necessary. For an example,
- see [PHP 8.1.6 released][].
+ sha256 hashes for the RC tarballs, but it's not necessary.
- Add, commit, and push your changes, when finished.
+9. Review all the changes in `web-php`, commit, and push them.
```shell
git add -p
- git commit --gpg-sign=YOURKEYID -m "PHP X.Y.Z released"
+ git add archive/entries/*.xml releases/*.php
+ git commit --gpg-sign=YOURKEYID -m "Announce PHP X.Y.Z"
git push upstream master
```
-11. 🚨 **Before sending announcement emails, check to make sure the websites have
+ See [Announce PHP 8.1.6][] for an example commit.
+
+10. 🚨 **Before sending announcement emails, check to make sure the websites have
synced.**
* Make sure the tarballs are available from, e.g.,
@@ -760,8 +748,8 @@ slightly different steps. We'll call attention where the steps differ.
e.g., https://www.php.net/ChangeLog-8.php
* Is there a release page for the new version?
e.g., `https://www.php.net/releases/X_Y_Z.php`
- * Does the RC for this version still appear on the QA home page?
- https://qa.php.net
+ * Does the RC for this version still appear on the Release Candidate Builds page?
+ https://www.php.net/release-candidates.php
Keep in mind it may take up to an hour for the websites to sync.
@@ -986,21 +974,22 @@ volunteers to begin the selection process for the next release managers.
## New release manager checklist
-1. Request membership to the
+1. Fill out [the form](https://www.php.net/git-php.php)
+ to get a PHP account (if you don't already have one).
+
+2. Request membership to the
[release managers group](https://github.com/orgs/php/teams/release-managers) on GitHub.
-2. Subscribe to the [email protected] mailing list by emailing
+3. Subscribe to the [email protected] mailing list by emailing
[email protected]
-3. Email [email protected] to get setup for access to downloads.php.net, to be
+4. Email [email protected] to get setup for access to downloads.php.net, to be
added to the [email protected] distribution list, and to be added to
the moderators for [email protected] so you are able to moderate
your release announcements.
Provide the following information in a single email:
- - Preferred Unix username (will also become part of location to download RCs,
- such as `https://downloads.php.net/~derick/`).
- An SSH public key, preferably a new unique one for PHP systems and
projects.
- Read [Machine Access](https://wiki.php.net/systems#machine_access) to set
@@ -1021,7 +1010,7 @@ volunteers to begin the selection process for the next release managers.
> "[Send emails from a different address or alias][]."
-4. Create a [GPG key][] for your @php.net address.
+5. Create a [GPG key][] for your @php.net address.
> 💡 **Tip** \
> If you're new to GPG, follow GitHub's instructions for
@@ -1086,11 +1075,10 @@ volunteers to begin the selection process for the next release managers.
git push
```
-5. Make sure you have the following repositories cloned locally:
+6. Make sure you have the following repositories cloned locally:
* https://github.com/php/php-src
* https://github.com/php/web-php
- * https://github.com/php/web-qa
* https://github.com/php/web-php-distributions
@@ -1105,13 +1093,10 @@ volunteers to begin the selection process for the next release managers.
[Update NEWS for PHP 8.2.0RC6]: https://github.com/php/php-src/commit/4ccc414961a70200d638ca281a35f893226d74e2
[PHP 8.3 is now for PHP 8.3.21-dev]: https://github.com/php/php-src/commit/b57f425cfe20a11003253427424cc0517483550b
[GitHub command line tool]: https://cli.github.com
-[Announce 8.1.0RC3]: https://github.com/php/web-qa/commit/f264b711fd3827803b79bbb342959eae57ea502b
-[8.1.6RC1]: https://github.com/php/web-qa/commit/e6d61ad7a9d8be0b1cd159af29f3b9cbdde33384
[merged upwards as usual]: https://wiki.php.net/vcs/gitworkflow
[Update versions for PHP 8.1.7]: https://github.com/php/php-src/commit/d35e577a1bd0b35b9386cea97cddc73fd98eed6d
[Update NEWS for PHP 8.1.7]: https://github.com/php/php-src/commit/b241f07f52ca9f87bf52be81817f475e6e727439
[Announce PHP 8.1.6]: https://github.com/php/web-php/commit/9f796a96c65f07e45845ec248933bfb0010b94a9
-[PHP 8.1.6 released]: https://github.com/php/web-qa/commit/bff725f8373cf6fd9d97ba62a8517b19721a4c2e
[feature freeze]: https://en.wikipedia.org/wiki/Freeze_(software_engineering)
[Prepare for PHP 8.2]: https://github.com/php/php-src/commit/1c33ddb5e5598c5385c4c965992c6e031fd00dd6
[Prepare for PHP 8.2 (bis)]: https://github.com/php/php-src/commit/a93e12f8a6dfc23e334339317c97aa35356db821
| diff --git a/docs/release-process.md b/docs/release-process.md
index 36963b4318ead..cbfa791db6ef5 100644
--- a/docs/release-process.md
+++ b/docs/release-process.md
@@ -73,7 +73,7 @@ releases.
> When you are unsure about anything, ask a previous RM before proceeding.
> Ideally, make sure a previous RM is available to answer questions during
> the first few releases of your version. For the steps related to the
- > `web-php`, `web-qa`, and `web-php-distributions` repositories, try to have
+ > `web-php` and `web-php-distributions` repositories, try to have
> someone from the webmaster team on hand.
5. Verify the tags to be extra sure everything was tagged properly.
@@ -325,7 +325,7 @@ slightly different steps. We'll call attention where the steps differ.
downloads.php.net.
```shell
- scp php-X.Y.ZRCn.tar.* downloads.php.net:~/public_html/
+ scp php-X.Y.ZRCn.tar.* downloads.internal.php.net:~/public_html/
```
> 💬 **Hint** \
@@ -359,11 +359,10 @@ slightly different steps. We'll call attention where the steps differ.
## Announcing a non-stable release (alpha/beta/RC)
-1. Switch to your local clone of the `web-qa` repository and update the
+1. Switch to your local clone of the `web-php` repository and update the
information in the `$QA_RELEASES` array in `include/release-qa.php`.
Follow the documentation in the file for editing the QA release information.
- See also [Announce 8.1.0RC3][] and [8.1.6RC1][] for examples.
Add, commit, and push your changes, when finished.
@@ -716,20 +715,7 @@ slightly different steps. We'll call attention where the steps differ.
./bin/news2html 'https://github.com/php/php-src/raw/php-X.Y.Z/NEWS' 'X.Y.Z' 'ChangeLog-X.php'
-9. Review all the changes in `web-php`, commit, and push them.
- ```shell
- git add -p
- git add archive/entries/*.xml releases/*.php
- git commit --gpg-sign=YOURKEYID -m "Announce PHP X.Y.Z"
- git push upstream master
- ```
-10. Switch to your local clone of the `web-qa` repository and update the
- information in the `$QA_RELEASES` array in `include/release-qa.php`.
+8. Update the information in the `$QA_RELEASES` array in `include/release-qa.php`.
The array probably contains information about the RC released two weeks ago
in preparation for the current release. Since the current release is now GA,
@@ -737,18 +723,20 @@ slightly different steps. We'll call attention where the steps differ.
It is sufficient to set the `number` property for the release to `0` to
stop displaying the RC build on the QA website. You may also remove the
- sha256 hashes for the RC tarballs, but it's not necessary. For an example,
+ sha256 hashes for the RC tarballs, but it's not necessary.
- Add, commit, and push your changes, when finished.
+9. Review all the changes in `web-php`, commit, and push them.
git add -p
- git commit --gpg-sign=YOURKEYID -m "PHP X.Y.Z released"
+ git commit --gpg-sign=YOURKEYID -m "Announce PHP X.Y.Z"
git push upstream master
-11. 🚨 **Before sending announcement emails, check to make sure the websites have
+ See [Announce PHP 8.1.6][] for an example commit.
+10. 🚨 **Before sending announcement emails, check to make sure the websites have
synced.**
* Make sure the tarballs are available from, e.g.,
@@ -760,8 +748,8 @@ slightly different steps. We'll call attention where the steps differ.
e.g., https://www.php.net/ChangeLog-8.php
* Is there a release page for the new version?
e.g., `https://www.php.net/releases/X_Y_Z.php`
- * Does the RC for this version still appear on the QA home page?
- https://qa.php.net
+ * Does the RC for this version still appear on the Release Candidate Builds page?
+ https://www.php.net/release-candidates.php
Keep in mind it may take up to an hour for the websites to sync.
@@ -986,21 +974,22 @@ volunteers to begin the selection process for the next release managers.
## New release manager checklist
-1. Request membership to the
+1. Fill out [the form](https://www.php.net/git-php.php)
+ to get a PHP account (if you don't already have one).
+2. Request membership to the
[release managers group](https://github.com/orgs/php/teams/release-managers) on GitHub.
+3. Subscribe to the [email protected] mailing list by emailing
[email protected]
-3. Email [email protected] to get setup for access to downloads.php.net, to be
+4. Email [email protected] to get setup for access to downloads.php.net, to be
added to the [email protected] distribution list, and to be added to
the moderators for [email protected] so you are able to moderate
your release announcements.
Provide the following information in a single email:
- - Preferred Unix username (will also become part of location to download RCs,
- such as `https://downloads.php.net/~derick/`).
- An SSH public key, preferably a new unique one for PHP systems and
projects.
- Read [Machine Access](https://wiki.php.net/systems#machine_access) to set
@@ -1021,7 +1010,7 @@ volunteers to begin the selection process for the next release managers.
> "[Send emails from a different address or alias][]."
-4. Create a [GPG key][] for your @php.net address.
+5. Create a [GPG key][] for your @php.net address.
> 💡 **Tip** \
> If you're new to GPG, follow GitHub's instructions for
@@ -1086,11 +1075,10 @@ volunteers to begin the selection process for the next release managers.
git push
-5. Make sure you have the following repositories cloned locally:
+6. Make sure you have the following repositories cloned locally:
* https://github.com/php/php-src
* https://github.com/php/web-php
* https://github.com/php/web-php-distributions
@@ -1105,13 +1093,10 @@ volunteers to begin the selection process for the next release managers.
[Update NEWS for PHP 8.2.0RC6]: https://github.com/php/php-src/commit/4ccc414961a70200d638ca281a35f893226d74e2
[PHP 8.3 is now for PHP 8.3.21-dev]: https://github.com/php/php-src/commit/b57f425cfe20a11003253427424cc0517483550b
[GitHub command line tool]: https://cli.github.com
-[Announce 8.1.0RC3]: https://github.com/php/web-qa/commit/f264b711fd3827803b79bbb342959eae57ea502b
-[8.1.6RC1]: https://github.com/php/web-qa/commit/e6d61ad7a9d8be0b1cd159af29f3b9cbdde33384
[merged upwards as usual]: https://wiki.php.net/vcs/gitworkflow
[Update versions for PHP 8.1.7]: https://github.com/php/php-src/commit/d35e577a1bd0b35b9386cea97cddc73fd98eed6d
[Update NEWS for PHP 8.1.7]: https://github.com/php/php-src/commit/b241f07f52ca9f87bf52be81817f475e6e727439
[Announce PHP 8.1.6]: https://github.com/php/web-php/commit/9f796a96c65f07e45845ec248933bfb0010b94a9
-[PHP 8.1.6 released]: https://github.com/php/web-qa/commit/bff725f8373cf6fd9d97ba62a8517b19721a4c2e
[feature freeze]: https://en.wikipedia.org/wiki/Freeze_(software_engineering)
[Prepare for PHP 8.2]: https://github.com/php/php-src/commit/1c33ddb5e5598c5385c4c965992c6e031fd00dd6
[Prepare for PHP 8.2 (bis)]: https://github.com/php/php-src/commit/a93e12f8a6dfc23e334339317c97aa35356db821 | [
"- See [Announce PHP 8.1.6][] for an example commit.",
"- see [PHP 8.1.6 released][].",
"+ git add archive/entries/*.xml releases/*.php",
"-2. Subscribe to the [email protected] mailing list by emailing",
"- * https://github.com/php/web-qa"
] | [
49,
62,
71,
105,
140
] | {
"additions": 21,
"author": "saundefined",
"deletions": 36,
"html_url": "https://github.com/php/php-src/pull/18342",
"issue_id": 18342,
"merged_at": "2025-04-24T15:53:11Z",
"omission_probability": 0.1,
"pr_number": 18342,
"repo": "php/php-src",
"title": "Update release process",
"total_changes": 57
} |
741 | diff --git a/ext/fileinfo/tests/bug79756.phpt b/ext/fileinfo/tests/bug79756.phpt
index b4ea28baaa9b..ad5478b62de8 100644
--- a/ext/fileinfo/tests/bug79756.phpt
+++ b/ext/fileinfo/tests/bug79756.phpt
@@ -7,7 +7,6 @@ fileinfo
$filename = __DIR__ . '/bug79756.xls';
$finfo = finfo_open(FILEINFO_MIME);
$mime = finfo_file($finfo, $filename);
-finfo_close($finfo);
echo $mime;
?>
--EXPECT--
diff --git a/ext/fileinfo/tests/cve-2014-1943-mb.phpt b/ext/fileinfo/tests/cve-2014-1943-mb.phpt
index 9dd4a9ec18a5..01cf70b811be 100644
--- a/ext/fileinfo/tests/cve-2014-1943-mb.phpt
+++ b/ext/fileinfo/tests/cve-2014-1943-mb.phpt
@@ -15,13 +15,11 @@ $m = "0 byte x\n".
file_put_contents($fd, $a);
$fi = finfo_open(FILEINFO_NONE);
var_dump(finfo_file($fi, $fd));
-finfo_close($fi);
file_put_contents($fd, $b);
file_put_contents($fm, $m);
$fi = finfo_open(FILEINFO_NONE, $fm);
var_dump(finfo_file($fi, $fd));
-finfo_close($fi);
?>
Done
--CLEAN--
diff --git a/ext/fileinfo/tests/cve-2014-1943.phpt b/ext/fileinfo/tests/cve-2014-1943.phpt
index 35f66148ae79..1aee196d16ff 100644
--- a/ext/fileinfo/tests/cve-2014-1943.phpt
+++ b/ext/fileinfo/tests/cve-2014-1943.phpt
@@ -15,13 +15,11 @@ $m = "0 byte x\n".
file_put_contents($fd, $a);
$fi = finfo_open(FILEINFO_NONE);
var_dump(finfo_file($fi, $fd));
-finfo_close($fi);
file_put_contents($fd, $b);
file_put_contents($fm, $m);
$fi = finfo_open(FILEINFO_NONE, $fm);
var_dump(finfo_file($fi, $fd));
-finfo_close($fi);
?>
Done
--CLEAN--
diff --git a/ext/fileinfo/tests/cve-2014-3538-mb.phpt b/ext/fileinfo/tests/cve-2014-3538-mb.phpt
index e6c63e35ac85..3b158a26b726 100644
--- a/ext/fileinfo/tests/cve-2014-3538-mb.phpt
+++ b/ext/fileinfo/tests/cve-2014-3538-mb.phpt
@@ -19,7 +19,6 @@ $fi = finfo_open(FILEINFO_NONE);
$t = microtime(true);
var_dump(finfo_file($fi, $fd));
$t = microtime(true) - $t;
-finfo_close($fi);
if ($t < 3) {
echo "Ok\n";
} else {
diff --git a/ext/fileinfo/tests/cve-2014-3538-nojit.phpt b/ext/fileinfo/tests/cve-2014-3538-nojit.phpt
index 2010d538da95..73ecd09561d8 100644
--- a/ext/fileinfo/tests/cve-2014-3538-nojit.phpt
+++ b/ext/fileinfo/tests/cve-2014-3538-nojit.phpt
@@ -23,7 +23,6 @@ $fi = finfo_open(FILEINFO_NONE);
$t = microtime(true);
var_dump(finfo_file($fi, $fd));
$t = microtime(true) - $t;
-finfo_close($fi);
if ($t < 1.5) {
echo "Ok\n";
} else {
diff --git a/ext/fileinfo/tests/cve-2014-3538.phpt b/ext/fileinfo/tests/cve-2014-3538.phpt
index f15e745fc05d..d19278d1dc32 100644
--- a/ext/fileinfo/tests/cve-2014-3538.phpt
+++ b/ext/fileinfo/tests/cve-2014-3538.phpt
@@ -19,7 +19,6 @@ $fi = finfo_open(FILEINFO_NONE);
$t = microtime(true);
var_dump(finfo_file($fi, $fd));
$t = microtime(true) - $t;
-finfo_close($fi);
if ($t < 1.5) {
echo "Ok\n";
} else {
diff --git a/ext/fileinfo/tests/finfo_buffer_basic-mb.phpt b/ext/fileinfo/tests/finfo_buffer_basic-mb.phpt
index 7426c909d976..0ed6d48c803c 100644
--- a/ext/fileinfo/tests/finfo_buffer_basic-mb.phpt
+++ b/ext/fileinfo/tests/finfo_buffer_basic-mb.phpt
@@ -27,7 +27,6 @@ foreach( $options as $option ) {
foreach( $buffers as $string ) {
var_dump( finfo_buffer( $finfo, $string, $option ) );
}
- finfo_close( $finfo );
}
?>
diff --git a/ext/fileinfo/tests/finfo_buffer_basic.phpt b/ext/fileinfo/tests/finfo_buffer_basic.phpt
index e338583fab70..6a6e6a7a862c 100644
--- a/ext/fileinfo/tests/finfo_buffer_basic.phpt
+++ b/ext/fileinfo/tests/finfo_buffer_basic.phpt
@@ -27,7 +27,6 @@ foreach( $options as $option ) {
foreach( $buffers as $string ) {
var_dump( finfo_buffer( $finfo, $string, $option ) );
}
- finfo_close( $finfo );
}
?>
diff --git a/ext/fileinfo/tests/finfo_set_flags_basic-mb.phpt b/ext/fileinfo/tests/finfo_set_flags_basic-mb.phpt
index f366972b613e..a4d723f86c9c 100644
--- a/ext/fileinfo/tests/finfo_set_flags_basic-mb.phpt
+++ b/ext/fileinfo/tests/finfo_set_flags_basic-mb.phpt
@@ -12,8 +12,6 @@ echo "*** Testing finfo_set_flags() : basic functionality ***\n";
var_dump( finfo_set_flags( $finfo, FILEINFO_NONE ) );
var_dump( finfo_set_flags( $finfo, FILEINFO_SYMLINK ) );
-finfo_close( $finfo );
-
// OO way
$finfo = new finfo( FILEINFO_NONE, $magicFile );
var_dump( $finfo->set_flags( FILEINFO_MIME ) );
diff --git a/ext/fileinfo/tests/finfo_set_flags_basic.phpt b/ext/fileinfo/tests/finfo_set_flags_basic.phpt
index 948031a0b800..db71447ae239 100644
--- a/ext/fileinfo/tests/finfo_set_flags_basic.phpt
+++ b/ext/fileinfo/tests/finfo_set_flags_basic.phpt
@@ -12,8 +12,6 @@ echo "*** Testing finfo_set_flags() : basic functionality ***\n";
var_dump( finfo_set_flags( $finfo, FILEINFO_NONE ) );
var_dump( finfo_set_flags( $finfo, FILEINFO_SYMLINK ) );
-finfo_close( $finfo );
-
// OO way
$finfo = new finfo( FILEINFO_NONE, $magicFile );
var_dump( $finfo->set_flags( FILEINFO_MIME ) );
diff --git a/ext/fileinfo/tests/finfo_upstream.phpt b/ext/fileinfo/tests/finfo_upstream.phpt
index ef5ec17b0370..2a28bd7f776c 100644
--- a/ext/fileinfo/tests/finfo_upstream.phpt
+++ b/ext/fileinfo/tests/finfo_upstream.phpt
@@ -18,7 +18,6 @@ foreach($lst as $p) {
if ($i !== $exp) {
echo "'$p' failed\nexp: '$exp'\ngot: '$i'\n";
}
- finfo_close($finfo);
}
echo "==DONE==";
| diff --git a/ext/fileinfo/tests/bug79756.phpt b/ext/fileinfo/tests/bug79756.phpt
index b4ea28baaa9b..ad5478b62de8 100644
--- a/ext/fileinfo/tests/bug79756.phpt
+++ b/ext/fileinfo/tests/bug79756.phpt
@@ -7,7 +7,6 @@ fileinfo
$filename = __DIR__ . '/bug79756.xls';
$finfo = finfo_open(FILEINFO_MIME);
$mime = finfo_file($finfo, $filename);
-finfo_close($finfo);
echo $mime;
--EXPECT--
diff --git a/ext/fileinfo/tests/cve-2014-1943-mb.phpt b/ext/fileinfo/tests/cve-2014-1943-mb.phpt
index 9dd4a9ec18a5..01cf70b811be 100644
--- a/ext/fileinfo/tests/cve-2014-1943-mb.phpt
+++ b/ext/fileinfo/tests/cve-2014-1943-mb.phpt
diff --git a/ext/fileinfo/tests/cve-2014-1943.phpt b/ext/fileinfo/tests/cve-2014-1943.phpt
index 35f66148ae79..1aee196d16ff 100644
--- a/ext/fileinfo/tests/cve-2014-1943.phpt
+++ b/ext/fileinfo/tests/cve-2014-1943.phpt
diff --git a/ext/fileinfo/tests/cve-2014-3538-mb.phpt b/ext/fileinfo/tests/cve-2014-3538-mb.phpt
index e6c63e35ac85..3b158a26b726 100644
--- a/ext/fileinfo/tests/cve-2014-3538-mb.phpt
+++ b/ext/fileinfo/tests/cve-2014-3538-mb.phpt
if ($t < 3) {
diff --git a/ext/fileinfo/tests/cve-2014-3538-nojit.phpt b/ext/fileinfo/tests/cve-2014-3538-nojit.phpt
index 2010d538da95..73ecd09561d8 100644
--- a/ext/fileinfo/tests/cve-2014-3538-nojit.phpt
+++ b/ext/fileinfo/tests/cve-2014-3538-nojit.phpt
@@ -23,7 +23,6 @@ $fi = finfo_open(FILEINFO_NONE);
diff --git a/ext/fileinfo/tests/cve-2014-3538.phpt b/ext/fileinfo/tests/cve-2014-3538.phpt
index f15e745fc05d..d19278d1dc32 100644
--- a/ext/fileinfo/tests/cve-2014-3538.phpt
+++ b/ext/fileinfo/tests/cve-2014-3538.phpt
diff --git a/ext/fileinfo/tests/finfo_buffer_basic-mb.phpt b/ext/fileinfo/tests/finfo_buffer_basic-mb.phpt
index 7426c909d976..0ed6d48c803c 100644
--- a/ext/fileinfo/tests/finfo_buffer_basic-mb.phpt
+++ b/ext/fileinfo/tests/finfo_buffer_basic-mb.phpt
diff --git a/ext/fileinfo/tests/finfo_buffer_basic.phpt b/ext/fileinfo/tests/finfo_buffer_basic.phpt
index e338583fab70..6a6e6a7a862c 100644
--- a/ext/fileinfo/tests/finfo_buffer_basic.phpt
+++ b/ext/fileinfo/tests/finfo_buffer_basic.phpt
diff --git a/ext/fileinfo/tests/finfo_set_flags_basic-mb.phpt b/ext/fileinfo/tests/finfo_set_flags_basic-mb.phpt
index f366972b613e..a4d723f86c9c 100644
--- a/ext/fileinfo/tests/finfo_set_flags_basic-mb.phpt
+++ b/ext/fileinfo/tests/finfo_set_flags_basic-mb.phpt
diff --git a/ext/fileinfo/tests/finfo_set_flags_basic.phpt b/ext/fileinfo/tests/finfo_set_flags_basic.phpt
index 948031a0b800..db71447ae239 100644
--- a/ext/fileinfo/tests/finfo_set_flags_basic.phpt
+++ b/ext/fileinfo/tests/finfo_set_flags_basic.phpt
diff --git a/ext/fileinfo/tests/finfo_upstream.phpt b/ext/fileinfo/tests/finfo_upstream.phpt
index ef5ec17b0370..2a28bd7f776c 100644
--- a/ext/fileinfo/tests/finfo_upstream.phpt
+++ b/ext/fileinfo/tests/finfo_upstream.phpt
@@ -18,7 +18,6 @@ foreach($lst as $p) {
if ($i !== $exp) {
echo "'$p' failed\nexp: '$exp'\ngot: '$i'\n";
}
- finfo_close($finfo);
echo "==DONE=="; | [] | [] | {
"additions": 0,
"author": "TimWolla",
"deletions": 15,
"html_url": "https://github.com/php/php-src/pull/18405",
"issue_id": 18405,
"merged_at": "2025-04-23T16:57:33Z",
"omission_probability": 0.1,
"pr_number": 18405,
"repo": "php/php-src",
"title": "fileinfo: Stop calling `finfo_close()` in tests",
"total_changes": 15
} |
742 | diff --git a/ext/fileinfo/fileinfo.c b/ext/fileinfo/fileinfo.c
index c0cc8877bf99..1dcc3346edfc 100644
--- a/ext/fileinfo/fileinfo.c
+++ b/ext/fileinfo/fileinfo.c
@@ -36,17 +36,11 @@
#include "fopen_wrappers.h" /* needed for is_url */
#include "Zend/zend_exceptions.h"
-/* {{{ macros and type definitions */
-typedef struct _php_fileinfo {
- zend_long options;
- struct magic_set *magic;
-} php_fileinfo;
-
static zend_object_handlers finfo_object_handlers;
zend_class_entry *finfo_class_entry;
typedef struct _finfo_object {
- php_fileinfo *ptr;
+ struct magic_set *magic;
zend_object zo;
} finfo_object;
@@ -56,26 +50,12 @@ static inline finfo_object *php_finfo_fetch_object(zend_object *obj) {
#define Z_FINFO_P(zv) php_finfo_fetch_object(Z_OBJ_P((zv)))
-#define FILEINFO_FROM_OBJECT(finfo, object) \
-{ \
- finfo_object *obj = Z_FINFO_P(object); \
- finfo = obj->ptr; \
- if (!finfo) { \
- zend_throw_error(NULL, "Invalid finfo object"); \
- RETURN_THROWS(); \
- } \
-}
-
/* {{{ finfo_objects_free */
static void finfo_objects_free(zend_object *object)
{
finfo_object *intern = php_finfo_fetch_object(object);
- if (intern->ptr) {
- magic_close(intern->ptr->magic);
- efree(intern->ptr);
- }
-
+ magic_close(intern->magic);
zend_object_std_dtor(&intern->zo);
}
/* }}} */
@@ -153,7 +133,6 @@ PHP_FUNCTION(finfo_open)
zend_long options = MAGIC_NONE;
char *file = NULL;
size_t file_len = 0;
- php_fileinfo *finfo;
zval *object = getThis();
char resolved_path[MAXPATHLEN];
zend_error_handling zeh;
@@ -163,15 +142,10 @@ PHP_FUNCTION(finfo_open)
}
if (object) {
- finfo_object *finfo_obj = Z_FINFO_P(object);
-
zend_replace_error_handling(EH_THROW, NULL, &zeh);
- if (finfo_obj->ptr) {
- magic_close(finfo_obj->ptr->magic);
- efree(finfo_obj->ptr);
- finfo_obj->ptr = NULL;
- }
+ magic_close(Z_FINFO_P(object)->magic);
+ Z_FINFO_P(object)->magic = NULL;
}
if (file_len == 0) {
@@ -199,13 +173,9 @@ PHP_FUNCTION(finfo_open)
file = resolved_path;
}
- finfo = emalloc(sizeof(php_fileinfo));
+ struct magic_set *magic = magic_open(options);
- finfo->options = options;
- finfo->magic = magic_open(options);
-
- if (finfo->magic == NULL) {
- efree(finfo);
+ if (magic == NULL) {
php_error_docref(NULL, E_WARNING, "Invalid mode '" ZEND_LONG_FMT "'.", options);
if (object) {
zend_restore_error_handling(&zeh);
@@ -216,10 +186,9 @@ PHP_FUNCTION(finfo_open)
RETURN_FALSE;
}
- if (magic_load(finfo->magic, file) == -1) {
+ if (magic_load(magic, file) == -1) {
php_error_docref(NULL, E_WARNING, "Failed to load magic database at \"%s\"", file);
- magic_close(finfo->magic);
- efree(finfo);
+ magic_close(magic);
if (object) {
zend_restore_error_handling(&zeh);
if (!EG(exception)) {
@@ -230,14 +199,13 @@ PHP_FUNCTION(finfo_open)
}
if (object) {
- finfo_object *obj;
zend_restore_error_handling(&zeh);
- obj = Z_FINFO_P(object);
- obj->ptr = finfo;
+ finfo_object *obj = Z_FINFO_P(object);
+ obj->magic = magic;
} else {
zend_object *zobj = finfo_objects_new(finfo_class_entry);
finfo_object *obj = php_finfo_fetch_object(zobj);
- obj->ptr = finfo;
+ obj->magic = magic;
RETURN_OBJ(zobj);
}
}
@@ -260,18 +228,20 @@ PHP_FUNCTION(finfo_close)
PHP_FUNCTION(finfo_set_flags)
{
zend_long options;
- php_fileinfo *finfo;
zval *self;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Ol", &self, finfo_class_entry, &options) == FAILURE) {
RETURN_THROWS();
}
- FILEINFO_FROM_OBJECT(finfo, self);
+
+ if (!Z_FINFO_P(self)->magic) {
+ zend_throw_error(NULL, "Invalid finfo object");
+ RETURN_THROWS();
+ }
/* We do not check the return value as it can only ever fail if options contains MAGIC_PRESERVE_ATIME
* and the system neither has utime(3) nor utimes(2). Something incredibly unlikely. */
- magic_setflags(finfo->magic, options);
- finfo->options = options;
+ magic_setflags(Z_FINFO_P(self)->magic, options);
RETURN_TRUE;
}
@@ -331,13 +301,17 @@ PHP_FUNCTION(finfo_file)
zend_string *path = NULL;
zend_long options = 0;
zval *zcontext = NULL;
- php_fileinfo *finfo = NULL;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OP|lr!", &self, finfo_class_entry, &path, &options, &zcontext) == FAILURE) {
RETURN_THROWS();
}
- FILEINFO_FROM_OBJECT(finfo, self);
- struct magic_set *magic = finfo->magic;
+
+ if (!Z_FINFO_P(self)->magic) {
+ zend_throw_error(NULL, "Invalid finfo object");
+ RETURN_THROWS();
+ }
+
+ struct magic_set *magic = Z_FINFO_P(self)->magic;
if (UNEXPECTED(ZSTR_LEN(path) == 0)) {
zend_argument_must_not_be_empty_error(2);
@@ -349,6 +323,7 @@ PHP_FUNCTION(finfo_file)
}
/* Set options for the current file/buffer. */
+ int old_options = magic_getflags(magic);
if (options) {
/* We do not check the return value as it can only ever fail if options contains MAGIC_PRESERVE_ATIME
* and the system neither has utime(3) nor utimes(2). Something incredibly unlikely. */
@@ -356,9 +331,10 @@ PHP_FUNCTION(finfo_file)
}
const char *ret_val = php_fileinfo_from_path(magic, path, context);
+
/* Restore options */
if (options) {
- magic_setflags(magic, finfo->options);
+ magic_setflags(magic, old_options);
}
if (UNEXPECTED(ret_val == NULL)) {
@@ -375,16 +351,23 @@ PHP_FUNCTION(finfo_buffer)
zend_string *buffer = NULL;
zend_long options = 0;
zval *dummy_context = NULL;
- php_fileinfo *finfo = NULL;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OS|lr!", &self, finfo_class_entry, &buffer, &options, &dummy_context) == FAILURE) {
RETURN_THROWS();
}
- FILEINFO_FROM_OBJECT(finfo, self);
- struct magic_set *magic = finfo->magic;
+
+ if (!Z_FINFO_P(self)->magic) {
+ zend_throw_error(NULL, "Invalid finfo object");
+ RETURN_THROWS();
+ }
+
+ struct magic_set *magic = Z_FINFO_P(self)->magic;
/* Set options for the current file/buffer. */
+ int old_options = magic_getflags(magic);
if (options) {
+ /* We do not check the return value as it can only ever fail if options contains MAGIC_PRESERVE_ATIME
+ * and the system neither has utime(3) nor utimes(2). Something incredibly unlikely. */
magic_setflags(magic, options);
}
@@ -392,7 +375,7 @@ PHP_FUNCTION(finfo_buffer)
/* Restore options */
if (options) {
- magic_setflags(magic, finfo->options);
+ magic_setflags(magic, old_options);
}
if (UNEXPECTED(ret_val == NULL)) {
diff --git a/ext/fileinfo/tests/finfo_uninitialized.phpt b/ext/fileinfo/tests/finfo_uninitialized.phpt
new file mode 100644
index 000000000000..533574c9c0dc
--- /dev/null
+++ b/ext/fileinfo/tests/finfo_uninitialized.phpt
@@ -0,0 +1,53 @@
+--TEST--
+Fileinfo uninitialized object
+--EXTENSIONS--
+fileinfo
+--FILE--
+<?php
+
+$finfo = (new ReflectionClass('finfo'))->newInstanceWithoutConstructor();
+
+try {
+ var_dump(finfo_set_flags($finfo, FILEINFO_NONE));
+} catch (Error $e) {
+ echo $e::class, ": ", $e->getMessage(), PHP_EOL;
+}
+
+try {
+ var_dump($finfo->set_flags(FILEINFO_NONE));
+} catch (Error $e) {
+ echo $e::class, ": ", $e->getMessage(), PHP_EOL;
+}
+
+try {
+ var_dump(finfo_file($finfo, __FILE__));
+} catch (Error $e) {
+ echo $e::class, ": ", $e->getMessage(), PHP_EOL;
+}
+
+try {
+ var_dump($finfo->file(__FILE__));
+} catch (Error $e) {
+ echo $e::class, ": ", $e->getMessage(), PHP_EOL;
+}
+
+try {
+ var_dump(finfo_buffer($finfo, file_get_contents(__FILE__)));
+} catch (Error $e) {
+ echo $e::class, ": ", $e->getMessage(), PHP_EOL;
+}
+
+try {
+ var_dump($finfo->file(file_get_contents(__FILE__)));
+} catch (Error $e) {
+ echo $e::class, ": ", $e->getMessage(), PHP_EOL;
+}
+
+?>
+--EXPECT--
+Error: Invalid finfo object
+Error: Invalid finfo object
+Error: Invalid finfo object
+Error: Invalid finfo object
+Error: Invalid finfo object
+Error: Invalid finfo object
| diff --git a/ext/fileinfo/fileinfo.c b/ext/fileinfo/fileinfo.c
index c0cc8877bf99..1dcc3346edfc 100644
--- a/ext/fileinfo/fileinfo.c
+++ b/ext/fileinfo/fileinfo.c
@@ -36,17 +36,11 @@
#include "fopen_wrappers.h" /* needed for is_url */
#include "Zend/zend_exceptions.h"
-/* {{{ macros and type definitions */
-typedef struct _php_fileinfo {
- zend_long options;
- struct magic_set *magic;
-} php_fileinfo;
static zend_object_handlers finfo_object_handlers;
zend_class_entry *finfo_class_entry;
typedef struct _finfo_object {
- php_fileinfo *ptr;
+ struct magic_set *magic;
zend_object zo;
} finfo_object;
@@ -56,26 +50,12 @@ static inline finfo_object *php_finfo_fetch_object(zend_object *obj) {
#define Z_FINFO_P(zv) php_finfo_fetch_object(Z_OBJ_P((zv)))
-#define FILEINFO_FROM_OBJECT(finfo, object) \
-{ \
- finfo_object *obj = Z_FINFO_P(object); \
- finfo = obj->ptr; \
- if (!finfo) { \
- RETURN_THROWS(); \
- } \
-}
/* {{{ finfo_objects_free */
static void finfo_objects_free(zend_object *object)
finfo_object *intern = php_finfo_fetch_object(object);
- if (intern->ptr) {
- efree(intern->ptr);
- }
+ magic_close(intern->magic);
zend_object_std_dtor(&intern->zo);
/* }}} */
@@ -153,7 +133,6 @@ PHP_FUNCTION(finfo_open)
zend_long options = MAGIC_NONE;
char *file = NULL;
size_t file_len = 0;
zval *object = getThis();
char resolved_path[MAXPATHLEN];
zend_error_handling zeh;
@@ -163,15 +142,10 @@ PHP_FUNCTION(finfo_open)
- finfo_object *finfo_obj = Z_FINFO_P(object);
zend_replace_error_handling(EH_THROW, NULL, &zeh);
- if (finfo_obj->ptr) {
- magic_close(finfo_obj->ptr->magic);
- efree(finfo_obj->ptr);
- finfo_obj->ptr = NULL;
+ magic_close(Z_FINFO_P(object)->magic);
+ Z_FINFO_P(object)->magic = NULL;
if (file_len == 0) {
@@ -199,13 +173,9 @@ PHP_FUNCTION(finfo_open)
file = resolved_path;
- finfo = emalloc(sizeof(php_fileinfo));
+ struct magic_set *magic = magic_open(options);
- if (finfo->magic == NULL) {
+ if (magic == NULL) {
php_error_docref(NULL, E_WARNING, "Invalid mode '" ZEND_LONG_FMT "'.", options);
@@ -216,10 +186,9 @@ PHP_FUNCTION(finfo_open)
RETURN_FALSE;
- if (magic_load(finfo->magic, file) == -1) {
+ if (magic_load(magic, file) == -1) {
php_error_docref(NULL, E_WARNING, "Failed to load magic database at \"%s\"", file);
- magic_close(finfo->magic);
+ magic_close(magic);
if (!EG(exception)) {
@@ -230,14 +199,13 @@ PHP_FUNCTION(finfo_open)
- finfo_object *obj;
zend_restore_error_handling(&zeh);
- obj = Z_FINFO_P(object);
+ finfo_object *obj = Z_FINFO_P(object);
} else {
zend_object *zobj = finfo_objects_new(finfo_class_entry);
finfo_object *obj = php_finfo_fetch_object(zobj);
RETURN_OBJ(zobj);
@@ -260,18 +228,20 @@ PHP_FUNCTION(finfo_close)
PHP_FUNCTION(finfo_set_flags)
zend_long options;
zval *self;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Ol", &self, finfo_class_entry, &options) == FAILURE) {
/* We do not check the return value as it can only ever fail if options contains MAGIC_PRESERVE_ATIME
* and the system neither has utime(3) nor utimes(2). Something incredibly unlikely. */
- magic_setflags(finfo->magic, options);
RETURN_TRUE;
@@ -331,13 +301,17 @@ PHP_FUNCTION(finfo_file)
zend_string *path = NULL;
zval *zcontext = NULL;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OP|lr!", &self, finfo_class_entry, &path, &options, &zcontext) == FAILURE) {
if (UNEXPECTED(ZSTR_LEN(path) == 0)) {
zend_argument_must_not_be_empty_error(2);
@@ -349,6 +323,7 @@ PHP_FUNCTION(finfo_file)
/* We do not check the return value as it can only ever fail if options contains MAGIC_PRESERVE_ATIME
* and the system neither has utime(3) nor utimes(2). Something incredibly unlikely. */
@@ -356,9 +331,10 @@ PHP_FUNCTION(finfo_file)
const char *ret_val = php_fileinfo_from_path(magic, path, context);
@@ -375,16 +351,23 @@ PHP_FUNCTION(finfo_buffer)
zend_string *buffer = NULL;
zval *dummy_context = NULL;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OS|lr!", &self, finfo_class_entry, &buffer, &options, &dummy_context) == FAILURE) {
+ /* We do not check the return value as it can only ever fail if options contains MAGIC_PRESERVE_ATIME
+ * and the system neither has utime(3) nor utimes(2). Something incredibly unlikely. */
magic_setflags(magic, options);
@@ -392,7 +375,7 @@ PHP_FUNCTION(finfo_buffer)
diff --git a/ext/fileinfo/tests/finfo_uninitialized.phpt b/ext/fileinfo/tests/finfo_uninitialized.phpt
new file mode 100644
index 000000000000..533574c9c0dc
--- /dev/null
+++ b/ext/fileinfo/tests/finfo_uninitialized.phpt
@@ -0,0 +1,53 @@
+--TEST--
+Fileinfo uninitialized object
+fileinfo
+--FILE--
+ var_dump($finfo->set_flags(FILEINFO_NONE));
+ var_dump(finfo_file($finfo, __FILE__));
+ var_dump(finfo_buffer($finfo, file_get_contents(__FILE__)));
+ var_dump($finfo->file(file_get_contents(__FILE__)));
+?>
+--EXPECT-- | [
"-\t\tzend_throw_error(NULL, \"Invalid finfo object\"); \\",
"-\t\tmagic_close(intern->ptr->magic);",
"-\t\t}",
"-\tfinfo->magic = magic_open(options);",
"+\tmagic_setflags(Z_FINFO_P(self)->magic, options);",
"+--EXTENSIONS--",
"+<?php",
"+$finfo = (new ReflectionClass('finfo'))->newInstanceWithoutConstructor();",
"+\tvar_dump(finfo_set_flags($finfo, FILEINFO_NONE));",
"+\tvar_dump($finfo->file(__FILE__));"
] | [
32,
43,
71,
85,
145,
234,
237,
239,
242,
260
] | {
"additions": 91,
"author": "TimWolla",
"deletions": 55,
"html_url": "https://github.com/php/php-src/pull/18398",
"issue_id": 18398,
"merged_at": "2025-04-23T10:04:11Z",
"omission_probability": 0.1,
"pr_number": 18398,
"repo": "php/php-src",
"title": "fileinfo: Remove `php_fileinfo` struct",
"total_changes": 146
} |
743 | diff --git a/NEWS b/NEWS
index bef0ac90460a..a3d278ac2e3b 100644
--- a/NEWS
+++ b/NEWS
@@ -88,6 +88,7 @@ PHP NEWS
(BogdanUngureanu)
. Added Locale::isRightToLeft to check if a locale is written right to left.
(David Carlier)
+ . Added null bytes presence in locale inputs for Locale class. (David Carlier)
- MySQLi:
. Fixed bugs GH-17900 and GH-8084 (calling mysqli::__construct twice).
diff --git a/UPGRADING b/UPGRADING
index 1b2779c8c1e7..40645a28ac60 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -212,6 +212,8 @@ PHP 8.5 UPGRADE NOTES
. grapheme_extract() properly assigns $next value when skipping over
invalid starting bytes. Previously there were cases where it would
point to the start of the grapheme boundary instead of the end.
+ . Locale:: methods throw a ValueError when locale inputs contain null
+ bytes.
- PCNTL:
. pcntl_exec() now has a formal return type of false.
diff --git a/ext/intl/locale/locale_methods.c b/ext/intl/locale/locale_methods.c
index bba52a90994c..684f84c7e323 100644
--- a/ext/intl/locale/locale_methods.c
+++ b/ext/intl/locale/locale_methods.c
@@ -315,7 +315,7 @@ PHP_NAMED_FUNCTION(zif_locale_set_default)
char *default_locale = NULL;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_STR(locale_name)
+ Z_PARAM_PATH_STR(locale_name)
ZEND_PARSE_PARAMETERS_END();
if (ZSTR_LEN(locale_name) == 0) {
@@ -481,7 +481,7 @@ static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS)
intl_error_reset( NULL );
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_STRING(loc_name, loc_name_len)
+ Z_PARAM_PATH(loc_name, loc_name_len)
ZEND_PARSE_PARAMETERS_END();
if(loc_name_len == 0) {
@@ -568,9 +568,9 @@ static void get_icu_disp_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAME
intl_error_reset( NULL );
ZEND_PARSE_PARAMETERS_START(1, 2)
- Z_PARAM_STRING(loc_name, loc_name_len)
+ Z_PARAM_PATH(loc_name, loc_name_len)
Z_PARAM_OPTIONAL
- Z_PARAM_STRING_OR_NULL(disp_loc_name, disp_loc_name_len)
+ Z_PARAM_PATH_OR_NULL(disp_loc_name, disp_loc_name_len)
ZEND_PARSE_PARAMETERS_END();
if(loc_name_len > ULOC_FULLNAME_CAPACITY) {
@@ -735,7 +735,7 @@ PHP_FUNCTION( locale_get_keywords )
intl_error_reset( NULL );
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_STRING(loc_name, loc_name_len)
+ Z_PARAM_PATH(loc_name, loc_name_len)
ZEND_PARSE_PARAMETERS_END();
INTL_CHECK_LOCALE_LEN(strlen(loc_name));
@@ -1126,7 +1126,7 @@ PHP_FUNCTION(locale_parse)
intl_error_reset( NULL );
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_STRING(loc_name, loc_name_len)
+ Z_PARAM_PATH(loc_name, loc_name_len)
ZEND_PARSE_PARAMETERS_END();
INTL_CHECK_LOCALE_LEN(strlen(loc_name));
@@ -1166,7 +1166,7 @@ PHP_FUNCTION(locale_get_all_variants)
intl_error_reset( NULL );
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_STRING(loc_name, loc_name_len)
+ Z_PARAM_PATH(loc_name, loc_name_len)
ZEND_PARSE_PARAMETERS_END();
if(loc_name_len == 0) {
@@ -1260,8 +1260,8 @@ PHP_FUNCTION(locale_filter_matches)
intl_error_reset( NULL );
ZEND_PARSE_PARAMETERS_START(2, 3)
- Z_PARAM_STRING(lang_tag, lang_tag_len)
- Z_PARAM_STRING(loc_range, loc_range_len)
+ Z_PARAM_PATH(lang_tag, lang_tag_len)
+ Z_PARAM_PATH(loc_range, loc_range_len)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL(boolCanonical)
ZEND_PARSE_PARAMETERS_END();
@@ -1434,6 +1434,10 @@ static zend_string* lookup_loc_range(const char* loc_range, HashTable* hash_arr,
zend_argument_type_error(2, "must only contain string values");
LOOKUP_CLEAN_RETURN(NULL);
}
+ if (zend_str_has_nul_byte(Z_STR_P(ele_value))) {
+ zend_argument_value_error(2, "must not contain any null bytes");
+ LOOKUP_CLEAN_RETURN(NULL);
+ }
cur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_P(ele_value), Z_STRLEN_P(ele_value));
result = strToMatch(Z_STRVAL_P(ele_value), cur_arr[cur_arr_len*2]);
if(result == 0) {
@@ -1535,10 +1539,10 @@ PHP_FUNCTION(locale_lookup)
ZEND_PARSE_PARAMETERS_START(2, 4)
Z_PARAM_ARRAY(arr)
- Z_PARAM_STRING(loc_range, loc_range_len)
+ Z_PARAM_PATH(loc_range, loc_range_len)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL(boolCanonical)
- Z_PARAM_STR_OR_NULL(fallback_loc_str)
+ Z_PARAM_PATH_STR_OR_NULL(fallback_loc_str)
ZEND_PARSE_PARAMETERS_END();
if(loc_range_len == 0) {
@@ -1626,7 +1630,7 @@ PHP_FUNCTION(locale_is_right_to_left)
size_t locale_len;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_STRING(locale, locale_len)
+ Z_PARAM_PATH(locale, locale_len)
ZEND_PARSE_PARAMETERS_END();
if (!locale_len) {
diff --git a/ext/intl/tests/locale_filter_matches_icu70.phpt b/ext/intl/tests/locale_filter_matches_icu70.phpt
index ce30b0565472..0e0b16af1760 100644
--- a/ext/intl/tests/locale_filter_matches_icu70.phpt
+++ b/ext/intl/tests/locale_filter_matches_icu70.phpt
@@ -69,6 +69,18 @@ function ut_main()
}
}
+ try {
+ ut_loc_locale_filter_matches("de\0-DE", "de-DE", false);
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
+ try {
+ ut_loc_locale_filter_matches("de-DE", "d\0e-DE", false);
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
$res_str .= "\n";
return $res_str;
@@ -79,6 +91,10 @@ ut_run();
?>
--EXPECT--
+Locale::filterMatches(): Argument #1 ($languageTag) must not contain any null bytes
+Locale::filterMatches(): Argument #2 ($locale) must not contain any null bytes
+locale_filter_matches(): Argument #1 ($languageTag) must not contain any null bytes
+locale_filter_matches(): Argument #2 ($locale) must not contain any null bytes
--------------
loc_range:de-de matches lang_tag de-DEVA ? NO
loc_range:de_DE canonically matches lang_tag de_Deva ? NO
diff --git a/ext/intl/tests/locale_get_all_variants.phpt b/ext/intl/tests/locale_get_all_variants.phpt
index 5b876d87eda9..12bf82cacac0 100644
--- a/ext/intl/tests/locale_get_all_variants.phpt
+++ b/ext/intl/tests/locale_get_all_variants.phpt
@@ -39,6 +39,12 @@ function ut_main()
$res_str .= "\n";
}
+ try {
+ ut_loc_locale_get_all_variants("i-\0tay");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
$res_str .= "\n";
return $res_str;
@@ -49,6 +55,8 @@ ut_run();
?>
--EXPECT--
+Locale::getAllVariants(): Argument #1 ($locale) must not contain any null bytes
+locale_get_all_variants(): Argument #1 ($locale) must not contain any null bytes
sl_IT_nedis_KIRTI : variants 'NEDIS','KIRTI',
sl_IT_nedis-a-kirti-x-xyz : variants 'NEDIS',
sl_IT_rozaj : variants 'ROZAJ',
diff --git a/ext/intl/tests/locale_get_display_language4.phpt b/ext/intl/tests/locale_get_display_language4.phpt
new file mode 100644
index 000000000000..1273c4a99968
--- /dev/null
+++ b/ext/intl/tests/locale_get_display_language4.phpt
@@ -0,0 +1,29 @@
+--TEST--
+locale_get_display_language() throwing null bytes exceptions.
+--EXTENSIONS--
+intl
+--FILE--
+<?php
+
+function ut_main()
+{
+ try {
+ ut_loc_get_display_language("a-D\0E", "locale=a-DE");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
+ try {
+ ut_loc_get_display_language("a-DE", "locale=a\0-DE");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+}
+include_once 'ut_common.inc';
+ut_run();
+?>
+--EXPECT--
+Locale::getDisplayLanguage(): Argument #1 ($locale) must not contain any null bytes
+Locale::getDisplayLanguage(): Argument #2 ($displayLocale) must not contain any null bytes
+locale_get_display_language(): Argument #1 ($locale) must not contain any null bytes
+locale_get_display_language(): Argument #2 ($displayLocale) must not contain any null bytes
diff --git a/ext/intl/tests/locale_get_display_script4.phpt b/ext/intl/tests/locale_get_display_script4.phpt
index 77c630393c88..533052933026 100644
--- a/ext/intl/tests/locale_get_display_script4.phpt
+++ b/ext/intl/tests/locale_get_display_script4.phpt
@@ -83,6 +83,18 @@ function ut_main()
$res_str .= "-----------------\n";
}
+ try {
+ ut_loc_get_display_script("a-D\0E", "locale=a-DE");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
+ try {
+ ut_loc_get_display_script("a-DE", "locale=a\0-DE");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
return $res_str;
}
@@ -92,6 +104,10 @@ ut_run();
?>
--EXPECT--
+Locale::getDisplayScript(): Argument #1 ($locale) must not contain any null bytes
+Locale::getDisplayScript(): Argument #2 ($displayLocale) must not contain any null bytes
+locale_get_display_script(): Argument #1 ($locale) must not contain any null bytes
+locale_get_display_script(): Argument #2 ($displayLocale) must not contain any null bytes
locale='uk-ua_CALIFORNIA@currency=;currency=GRN'
disp_locale=en : display_script=
disp_locale=fr : display_script=
diff --git a/ext/intl/tests/locale_get_region.phpt b/ext/intl/tests/locale_get_region.phpt
index f843397bdb6c..0c3c1655deb3 100644
--- a/ext/intl/tests/locale_get_region.phpt
+++ b/ext/intl/tests/locale_get_region.phpt
@@ -76,6 +76,12 @@ function ut_main()
$res_str .= "\n";
}
+ try {
+ ut_loc_get_region("a-\0DE");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
return $res_str;
}
@@ -85,6 +91,8 @@ ut_run();
?>
--EXPECTF--
+Locale::getRegion(): Argument #1 ($locale) must not contain any null bytes
+locale_get_region(): Argument #1 ($locale) must not contain any null bytes
uk-ua_CALIFORNIA@currency=;currency=GRN: region='UA'
root: region=''
uk@currency=EURO: region=''
diff --git a/ext/intl/tests/locale_get_script.phpt b/ext/intl/tests/locale_get_script.phpt
index e00c83626d5b..52e0a4155a97 100644
--- a/ext/intl/tests/locale_get_script.phpt
+++ b/ext/intl/tests/locale_get_script.phpt
@@ -74,6 +74,12 @@ function ut_main()
$res_str .= "\n";
}
+ try {
+ ut_loc_get_script("de\0-419-DE");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
return $res_str;
}
@@ -83,6 +89,8 @@ ut_run();
?>
--EXPECT--
+Locale::getScript(): Argument #1 ($locale) must not contain any null bytes
+locale_get_script(): Argument #1 ($locale) must not contain any null bytes
uk-ua_CALIFORNIA@currency=;currency=GRN: script=''
root: script=''
uk@currency=EURO: script=''
diff --git a/ext/intl/tests/locale_is_right_to_left.phpt b/ext/intl/tests/locale_is_right_to_left.phpt
index c586582d4222..c9e4323ff744 100644
--- a/ext/intl/tests/locale_is_right_to_left.phpt
+++ b/ext/intl/tests/locale_is_right_to_left.phpt
@@ -8,9 +8,15 @@ var_dump(Locale::isRightToLeft("en-US"));
var_dump(Locale::isRightToLeft("\INVALID\\"));
var_dump(Locale::isRightToLeft(""));
var_dump(Locale::isRightToLeft("ar"));
+try {
+ Locale::isRightToLeft("a\0r");
+} catch (\ValueError $e) {
+ echo $e->getMessage();
+}
?>
--EXPECT--
bool(false)
bool(false)
bool(false)
bool(true)
+Locale::isRightToLeft(): Argument #1 ($locale) must not contain any null bytes
diff --git a/ext/intl/tests/locale_lookup_variant3.phpt b/ext/intl/tests/locale_lookup_variant3.phpt
index c1741a0ed9dd..b13a54139f44 100644
--- a/ext/intl/tests/locale_lookup_variant3.phpt
+++ b/ext/intl/tests/locale_lookup_variant3.phpt
@@ -59,6 +59,24 @@ function ut_main()
}
+ try {
+ ut_loc_locale_lookup(["de\0-DE"], "de-DE", false, "en-US");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
+ try {
+ ut_loc_locale_lookup(["de-DE"], "de-D\0E", true, "en-US");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
+ try {
+ ut_loc_locale_lookup(["de-DE"], "de-DE", true, "e\0n-US");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(). PHP_EOL;
+ }
+
$res_str .= "\n";
return $res_str;
@@ -69,6 +87,12 @@ ut_run();
?>
--EXPECT--
+Locale::lookup(): Argument #2 ($locale) must not contain any null bytes
+Locale::lookup(): Argument #2 ($locale) must not contain any null bytes
+Locale::lookup(): Argument #4 ($defaultLocale) must not contain any null bytes
+locale_lookup(): Argument #2 ($locale) must not contain any null bytes
+locale_lookup(): Argument #2 ($locale) must not contain any null bytes
+locale_lookup(): Argument #4 ($defaultLocale) must not contain any null bytes
--------------
loc_range:de-de
lang_tags: de-DEVA,de-DE-1996,de-DE,zh_Hans,de-CH-1996,sl_IT,sl_IT_nedis-a-kirti-x-xyz,sl_IT_rozaj,sl_IT_NEDIS_ROJAZ_1901,i-enochian,sgn-CH-de,art-lojban,i-lux,art-lojban,jbo,en_sl_IT,zh-Hant-CN-x-prv1-prv2
diff --git a/ext/intl/tests/locale_set_default.phpt b/ext/intl/tests/locale_set_default.phpt
index 0f690aabc296..6108f370274b 100644
--- a/ext/intl/tests/locale_set_default.phpt
+++ b/ext/intl/tests/locale_set_default.phpt
@@ -86,6 +86,12 @@ function ut_main()
$res_str .= "\n";
}
+ try {
+ ut_loc_set_default("a-\0DE");
+ } catch (\ValueError $e) {
+ echo $e->getMessage(), PHP_EOL;
+ }
+
return $res_str;
}
@@ -95,6 +101,8 @@ ut_run();
?>
--EXPECT--
+Locale::setDefault(): Argument #1 ($locale) must not contain any null bytes
+locale_set_default(): Argument #1 ($locale) must not contain any null bytes
uk-ua_CALIFORNIA@currency=;currency=GRN: set locale 'uk-ua_CALIFORNIA@currency=;currency=GRN'
root: set locale 'root'
uk@currency=EURO: set locale 'uk@currency=EURO'
| diff --git a/NEWS b/NEWS
index bef0ac90460a..a3d278ac2e3b 100644
--- a/NEWS
+++ b/NEWS
@@ -88,6 +88,7 @@ PHP NEWS
(BogdanUngureanu)
. Added Locale::isRightToLeft to check if a locale is written right to left.
(David Carlier)
+ . Added null bytes presence in locale inputs for Locale class. (David Carlier)
- MySQLi:
. Fixed bugs GH-17900 and GH-8084 (calling mysqli::__construct twice).
diff --git a/UPGRADING b/UPGRADING
index 1b2779c8c1e7..40645a28ac60 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -212,6 +212,8 @@ PHP 8.5 UPGRADE NOTES
. grapheme_extract() properly assigns $next value when skipping over
invalid starting bytes. Previously there were cases where it would
point to the start of the grapheme boundary instead of the end.
+ . Locale:: methods throw a ValueError when locale inputs contain null
+ bytes.
- PCNTL:
. pcntl_exec() now has a formal return type of false.
diff --git a/ext/intl/locale/locale_methods.c b/ext/intl/locale/locale_methods.c
index bba52a90994c..684f84c7e323 100644
--- a/ext/intl/locale/locale_methods.c
+++ b/ext/intl/locale/locale_methods.c
@@ -315,7 +315,7 @@ PHP_NAMED_FUNCTION(zif_locale_set_default)
char *default_locale = NULL;
- Z_PARAM_STR(locale_name)
+ Z_PARAM_PATH_STR(locale_name)
if (ZSTR_LEN(locale_name) == 0) {
@@ -481,7 +481,7 @@ static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS)
@@ -568,9 +568,9 @@ static void get_icu_disp_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAME
ZEND_PARSE_PARAMETERS_START(1, 2)
- Z_PARAM_STRING_OR_NULL(disp_loc_name, disp_loc_name_len)
+ Z_PARAM_PATH_OR_NULL(disp_loc_name, disp_loc_name_len)
if(loc_name_len > ULOC_FULLNAME_CAPACITY) {
@@ -735,7 +735,7 @@ PHP_FUNCTION( locale_get_keywords )
@@ -1126,7 +1126,7 @@ PHP_FUNCTION(locale_parse)
@@ -1166,7 +1166,7 @@ PHP_FUNCTION(locale_get_all_variants)
@@ -1260,8 +1260,8 @@ PHP_FUNCTION(locale_filter_matches)
ZEND_PARSE_PARAMETERS_START(2, 3)
- Z_PARAM_STRING(lang_tag, lang_tag_len)
- Z_PARAM_STRING(loc_range, loc_range_len)
+ Z_PARAM_PATH(lang_tag, lang_tag_len)
+ Z_PARAM_PATH(loc_range, loc_range_len)
@@ -1434,6 +1434,10 @@ static zend_string* lookup_loc_range(const char* loc_range, HashTable* hash_arr,
zend_argument_type_error(2, "must only contain string values");
LOOKUP_CLEAN_RETURN(NULL);
}
+ if (zend_str_has_nul_byte(Z_STR_P(ele_value))) {
+ zend_argument_value_error(2, "must not contain any null bytes");
+ LOOKUP_CLEAN_RETURN(NULL);
+ }
cur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_P(ele_value), Z_STRLEN_P(ele_value));
result = strToMatch(Z_STRVAL_P(ele_value), cur_arr[cur_arr_len*2]);
if(result == 0) {
@@ -1535,10 +1539,10 @@ PHP_FUNCTION(locale_lookup)
ZEND_PARSE_PARAMETERS_START(2, 4)
Z_PARAM_ARRAY(arr)
- Z_PARAM_STRING(loc_range, loc_range_len)
+ Z_PARAM_PATH(loc_range, loc_range_len)
- Z_PARAM_STR_OR_NULL(fallback_loc_str)
+ Z_PARAM_PATH_STR_OR_NULL(fallback_loc_str)
if(loc_range_len == 0) {
@@ -1626,7 +1630,7 @@ PHP_FUNCTION(locale_is_right_to_left)
size_t locale_len;
- Z_PARAM_STRING(locale, locale_len)
+ Z_PARAM_PATH(locale, locale_len)
if (!locale_len) {
diff --git a/ext/intl/tests/locale_filter_matches_icu70.phpt b/ext/intl/tests/locale_filter_matches_icu70.phpt
index ce30b0565472..0e0b16af1760 100644
--- a/ext/intl/tests/locale_filter_matches_icu70.phpt
+++ b/ext/intl/tests/locale_filter_matches_icu70.phpt
@@ -69,6 +69,18 @@ function ut_main()
}
+ ut_loc_locale_filter_matches("de\0-DE", "de-DE", false);
+ ut_loc_locale_filter_matches("de-DE", "d\0e-DE", false);
@@ -79,6 +91,10 @@ ut_run();
+Locale::filterMatches(): Argument #1 ($languageTag) must not contain any null bytes
+Locale::filterMatches(): Argument #2 ($locale) must not contain any null bytes
+locale_filter_matches(): Argument #1 ($languageTag) must not contain any null bytes
+locale_filter_matches(): Argument #2 ($locale) must not contain any null bytes
loc_range:de-de matches lang_tag de-DEVA ? NO
loc_range:de_DE canonically matches lang_tag de_Deva ? NO
diff --git a/ext/intl/tests/locale_get_all_variants.phpt b/ext/intl/tests/locale_get_all_variants.phpt
index 5b876d87eda9..12bf82cacac0 100644
--- a/ext/intl/tests/locale_get_all_variants.phpt
+++ b/ext/intl/tests/locale_get_all_variants.phpt
@@ -39,6 +39,12 @@ function ut_main()
+ ut_loc_locale_get_all_variants("i-\0tay");
@@ -49,6 +55,8 @@ ut_run();
+Locale::getAllVariants(): Argument #1 ($locale) must not contain any null bytes
+locale_get_all_variants(): Argument #1 ($locale) must not contain any null bytes
sl_IT_nedis_KIRTI : variants 'NEDIS','KIRTI',
sl_IT_nedis-a-kirti-x-xyz : variants 'NEDIS',
sl_IT_rozaj : variants 'ROZAJ',
diff --git a/ext/intl/tests/locale_get_display_language4.phpt b/ext/intl/tests/locale_get_display_language4.phpt
new file mode 100644
index 000000000000..1273c4a99968
--- /dev/null
+++ b/ext/intl/tests/locale_get_display_language4.phpt
@@ -0,0 +1,29 @@
+--TEST--
+locale_get_display_language() throwing null bytes exceptions.
+--EXTENSIONS--
+intl
+--FILE--
+<?php
+function ut_main()
+ ut_loc_get_display_language("a-D\0E", "locale=a-DE");
+ ut_loc_get_display_language("a-DE", "locale=a\0-DE");
+include_once 'ut_common.inc';
+ut_run();
+--EXPECT--
+Locale::getDisplayLanguage(): Argument #1 ($locale) must not contain any null bytes
+Locale::getDisplayLanguage(): Argument #2 ($displayLocale) must not contain any null bytes
+locale_get_display_language(): Argument #1 ($locale) must not contain any null bytes
+locale_get_display_language(): Argument #2 ($displayLocale) must not contain any null bytes
diff --git a/ext/intl/tests/locale_get_display_script4.phpt b/ext/intl/tests/locale_get_display_script4.phpt
index 77c630393c88..533052933026 100644
--- a/ext/intl/tests/locale_get_display_script4.phpt
+++ b/ext/intl/tests/locale_get_display_script4.phpt
@@ -83,6 +83,18 @@ function ut_main()
$res_str .= "-----------------\n";
+ ut_loc_get_display_script("a-D\0E", "locale=a-DE");
@@ -92,6 +104,10 @@ ut_run();
+Locale::getDisplayScript(): Argument #1 ($locale) must not contain any null bytes
+Locale::getDisplayScript(): Argument #2 ($displayLocale) must not contain any null bytes
+locale_get_display_script(): Argument #1 ($locale) must not contain any null bytes
+locale_get_display_script(): Argument #2 ($displayLocale) must not contain any null bytes
locale='uk-ua_CALIFORNIA@currency=;currency=GRN'
disp_locale=en : display_script=
disp_locale=fr : display_script=
diff --git a/ext/intl/tests/locale_get_region.phpt b/ext/intl/tests/locale_get_region.phpt
index f843397bdb6c..0c3c1655deb3 100644
--- a/ext/intl/tests/locale_get_region.phpt
+++ b/ext/intl/tests/locale_get_region.phpt
@@ -76,6 +76,12 @@ function ut_main()
+ ut_loc_get_region("a-\0DE");
@@ -85,6 +91,8 @@ ut_run();
--EXPECTF--
+locale_get_region(): Argument #1 ($locale) must not contain any null bytes
uk-ua_CALIFORNIA@currency=;currency=GRN: region='UA'
root: region=''
uk@currency=EURO: region=''
diff --git a/ext/intl/tests/locale_get_script.phpt b/ext/intl/tests/locale_get_script.phpt
index e00c83626d5b..52e0a4155a97 100644
--- a/ext/intl/tests/locale_get_script.phpt
+++ b/ext/intl/tests/locale_get_script.phpt
@@ -74,6 +74,12 @@ function ut_main()
+ ut_loc_get_script("de\0-419-DE");
@@ -83,6 +89,8 @@ ut_run();
+Locale::getScript(): Argument #1 ($locale) must not contain any null bytes
+locale_get_script(): Argument #1 ($locale) must not contain any null bytes
uk-ua_CALIFORNIA@currency=;currency=GRN: script=''
root: script=''
uk@currency=EURO: script=''
diff --git a/ext/intl/tests/locale_is_right_to_left.phpt b/ext/intl/tests/locale_is_right_to_left.phpt
index c586582d4222..c9e4323ff744 100644
--- a/ext/intl/tests/locale_is_right_to_left.phpt
+++ b/ext/intl/tests/locale_is_right_to_left.phpt
@@ -8,9 +8,15 @@ var_dump(Locale::isRightToLeft("en-US"));
var_dump(Locale::isRightToLeft("\INVALID\\"));
var_dump(Locale::isRightToLeft(""));
var_dump(Locale::isRightToLeft("ar"));
+try {
+ Locale::isRightToLeft("a\0r");
+} catch (\ValueError $e) {
+ echo $e->getMessage();
bool(true)
+Locale::isRightToLeft(): Argument #1 ($locale) must not contain any null bytes
diff --git a/ext/intl/tests/locale_lookup_variant3.phpt b/ext/intl/tests/locale_lookup_variant3.phpt
index c1741a0ed9dd..b13a54139f44 100644
--- a/ext/intl/tests/locale_lookup_variant3.phpt
+++ b/ext/intl/tests/locale_lookup_variant3.phpt
@@ -59,6 +59,24 @@ function ut_main()
+ ut_loc_locale_lookup(["de\0-DE"], "de-DE", false, "en-US");
+ ut_loc_locale_lookup(["de-DE"], "de-D\0E", true, "en-US");
+ ut_loc_locale_lookup(["de-DE"], "de-DE", true, "e\0n-US");
@@ -69,6 +87,12 @@ ut_run();
+locale_lookup(): Argument #4 ($defaultLocale) must not contain any null bytes
loc_range:de-de
lang_tags: de-DEVA,de-DE-1996,de-DE,zh_Hans,de-CH-1996,sl_IT,sl_IT_nedis-a-kirti-x-xyz,sl_IT_rozaj,sl_IT_NEDIS_ROJAZ_1901,i-enochian,sgn-CH-de,art-lojban,i-lux,art-lojban,jbo,en_sl_IT,zh-Hant-CN-x-prv1-prv2
diff --git a/ext/intl/tests/locale_set_default.phpt b/ext/intl/tests/locale_set_default.phpt
index 0f690aabc296..6108f370274b 100644
--- a/ext/intl/tests/locale_set_default.phpt
+++ b/ext/intl/tests/locale_set_default.phpt
@@ -86,6 +86,12 @@ function ut_main()
+ ut_loc_set_default("a-\0DE");
@@ -95,6 +101,8 @@ ut_run();
+Locale::setDefault(): Argument #1 ($locale) must not contain any null bytes
+locale_set_default(): Argument #1 ($locale) must not contain any null bytes
uk-ua_CALIFORNIA@currency=;currency=GRN: set locale 'uk-ua_CALIFORNIA@currency=;currency=GRN'
root: set locale 'root'
uk@currency=EURO: set locale 'uk@currency=EURO' | [
"+{",
"+?>",
"+\t ut_loc_get_display_script(\"a-DE\", \"locale=a\\0-DE\");",
"+Locale::getRegion(): Argument #1 ($locale) must not contain any null bytes",
"+Locale::lookup(): Argument #4 ($defaultLocale) must not contain any null bytes",
"+ echo $e->getMessage(), PHP_EOL;"
] | [
204,
219,
240,
280,
366,
384
] | {
"additions": 142,
"author": "devnexen",
"deletions": 12,
"html_url": "https://github.com/php/php-src/pull/18365",
"issue_id": 18365,
"merged_at": "2025-04-22T22:39:05Z",
"omission_probability": 0.1,
"pr_number": 18365,
"repo": "php/php-src",
"title": "ext/intl: Locale::* methods using param as path whenever relevant.",
"total_changes": 154
} |
744 | diff --git a/NEWS b/NEWS
index 47bf820d6b64..bef0ac90460a 100644
--- a/NEWS
+++ b/NEWS
@@ -69,6 +69,7 @@ PHP NEWS
- Fileinfo:
. Upgrade to file 5.46. (nielsdos)
+ . Change return type of finfo_close() to true. (timwolla)
- FPM:
. Fixed GH-17645 (FPM with httpd ProxyPass does not decode script path).
diff --git a/UPGRADING b/UPGRADING
index 6b6c555adcf7..36be5313ab6c 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -348,6 +348,9 @@ PHP 8.5 UPGRADE NOTES
- Fileinfo:
. Upgraded to file 5.46.
+ . The return type of finfo_close() has been changed to true, rather
+ than bool.
+
- PCRE:
. Upgraded to pcre2lib from 10.44 to 10.45.
diff --git a/ext/fileinfo/fileinfo.stub.php b/ext/fileinfo/fileinfo.stub.php
index 6fc2cc4c7b4e..2dba0fe2659e 100644
--- a/ext/fileinfo/fileinfo.stub.php
+++ b/ext/fileinfo/fileinfo.stub.php
@@ -92,7 +92,7 @@ public function set_flags(int $flags): true {}
/** @refcount 1 */
function finfo_open(int $flags = FILEINFO_NONE, ?string $magic_database = null): finfo|false {}
-function finfo_close(finfo $finfo): bool {}
+function finfo_close(finfo $finfo): true {}
function finfo_set_flags(finfo $finfo, int $flags): true {}
diff --git a/ext/fileinfo/fileinfo_arginfo.h b/ext/fileinfo/fileinfo_arginfo.h
index 36b9351ea138..024e7d4b6bd5 100644
--- a/ext/fileinfo/fileinfo_arginfo.h
+++ b/ext/fileinfo/fileinfo_arginfo.h
@@ -1,12 +1,12 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: 96d78126bc5af37c5d94fa160e509623e947de48 */
+ * Stub hash: d5bc322159e4af87077c07ddaca0a77803b4743a */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_finfo_open, 0, 0, finfo, MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "FILEINFO_NONE")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, magic_database, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
-ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_finfo_close, 0, 1, _IS_BOOL, 0)
+ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_finfo_close, 0, 1, IS_TRUE, 0)
ZEND_ARG_OBJ_INFO(0, finfo, finfo, 0)
ZEND_END_ARG_INFO()
| diff --git a/NEWS b/NEWS
index 47bf820d6b64..bef0ac90460a 100644
--- a/NEWS
+++ b/NEWS
@@ -69,6 +69,7 @@ PHP NEWS
. Upgrade to file 5.46. (nielsdos)
+ . Change return type of finfo_close() to true. (timwolla)
- FPM:
. Fixed GH-17645 (FPM with httpd ProxyPass does not decode script path).
diff --git a/UPGRADING b/UPGRADING
index 6b6c555adcf7..36be5313ab6c 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -348,6 +348,9 @@ PHP 8.5 UPGRADE NOTES
. Upgraded to file 5.46.
+ . The return type of finfo_close() has been changed to true, rather
+ than bool.
+
- PCRE:
. Upgraded to pcre2lib from 10.44 to 10.45.
diff --git a/ext/fileinfo/fileinfo.stub.php b/ext/fileinfo/fileinfo.stub.php
index 6fc2cc4c7b4e..2dba0fe2659e 100644
--- a/ext/fileinfo/fileinfo.stub.php
+++ b/ext/fileinfo/fileinfo.stub.php
@@ -92,7 +92,7 @@ public function set_flags(int $flags): true {}
/** @refcount 1 */
function finfo_open(int $flags = FILEINFO_NONE, ?string $magic_database = null): finfo|false {}
-function finfo_close(finfo $finfo): bool {}
+function finfo_close(finfo $finfo): true {}
function finfo_set_flags(finfo $finfo, int $flags): true {}
diff --git a/ext/fileinfo/fileinfo_arginfo.h b/ext/fileinfo/fileinfo_arginfo.h
index 36b9351ea138..024e7d4b6bd5 100644
--- a/ext/fileinfo/fileinfo_arginfo.h
+++ b/ext/fileinfo/fileinfo_arginfo.h
@@ -1,12 +1,12 @@
/* This is a generated file, edit the .stub.php file instead.
+ * Stub hash: d5bc322159e4af87077c07ddaca0a77803b4743a */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_finfo_open, 0, 0, finfo, MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "FILEINFO_NONE")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, magic_database, IS_STRING, 1, "null")
-ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_finfo_close, 0, 1, _IS_BOOL, 0)
+ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_finfo_close, 0, 1, IS_TRUE, 0)
ZEND_ARG_OBJ_INFO(0, finfo, finfo, 0) | [
"- * Stub hash: 96d78126bc5af37c5d94fa160e509623e947de48 */"
] | [
45
] | {
"additions": 7,
"author": "TimWolla",
"deletions": 3,
"html_url": "https://github.com/php/php-src/pull/18395",
"issue_id": 18395,
"merged_at": "2025-04-22T18:18:08Z",
"omission_probability": 0.1,
"pr_number": 18395,
"repo": "php/php-src",
"title": "fileinfo: Change return type of `finfo_close()` to `true`",
"total_changes": 10
} |
745 | diff --git a/ext/pgsql/pgsql.c b/ext/pgsql/pgsql.c
index c53bf8ed9a35c..745b247c66130 100644
--- a/ext/pgsql/pgsql.c
+++ b/ext/pgsql/pgsql.c
@@ -2186,17 +2186,18 @@ PHP_FUNCTION(pg_fetch_all_columns)
RETURN_THROWS();
}
- array_init(return_value);
-
if ((pg_numrows = PQntuples(pgsql_result)) <= 0) {
- return;
+ RETURN_EMPTY_ARRAY();
}
+ array_init_size(return_value, pg_numrows);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
+
for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
if (PQgetisnull(pgsql_result, pg_row, (int)colno)) {
- add_next_index_null(return_value);
+ add_index_null(return_value, pg_row);
} else {
- add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, (int)colno));
+ add_index_string(return_value, pg_row, PQgetvalue(pgsql_result, pg_row, (int)colno));
}
}
}
@@ -3363,6 +3364,7 @@ PHP_FUNCTION(pg_copy_to)
PQclear(pgsql_result);
array_init(return_value);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
while (!copydone)
{
int ret = PQgetCopyData(pgsql, &csv, 0);
| diff --git a/ext/pgsql/pgsql.c b/ext/pgsql/pgsql.c
index c53bf8ed9a35c..745b247c66130 100644
--- a/ext/pgsql/pgsql.c
+++ b/ext/pgsql/pgsql.c
@@ -2186,17 +2186,18 @@ PHP_FUNCTION(pg_fetch_all_columns)
RETURN_THROWS();
- array_init(return_value);
-
if ((pg_numrows = PQntuples(pgsql_result)) <= 0) {
- return;
+ RETURN_EMPTY_ARRAY();
+ array_init_size(return_value, pg_numrows);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
+
for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
if (PQgetisnull(pgsql_result, pg_row, (int)colno)) {
+ add_index_null(return_value, pg_row);
} else {
- add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, (int)colno));
}
}
@@ -3363,6 +3364,7 @@ PHP_FUNCTION(pg_copy_to)
PQclear(pgsql_result);
array_init(return_value);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
while (!copydone)
{
int ret = PQgetCopyData(pgsql, &csv, 0); | [
"-\t\t\tadd_next_index_null(return_value);",
"+\t\t\tadd_index_string(return_value, pg_row, PQgetvalue(pgsql_result, pg_row, (int)colno));"
] | [
20,
24
] | {
"additions": 7,
"author": "devnexen",
"deletions": 5,
"html_url": "https://github.com/php/php-src/pull/18374",
"issue_id": 18374,
"merged_at": "2025-04-21T12:43:44Z",
"omission_probability": 0.1,
"pr_number": 18374,
"repo": "php/php-src",
"title": "ext/pgsql: pg_fetch_all_columns/pg_copy_to arrays optimisations.",
"total_changes": 12
} |
746 | diff --git a/ext/posix/posix.c b/ext/posix/posix.c
index d465e5230938a..68d47840c5e20 100644
--- a/ext/posix/posix.c
+++ b/ext/posix/posix.c
@@ -236,10 +236,11 @@ PHP_FUNCTION(posix_getgroups)
RETURN_FALSE;
}
- array_init(return_value);
+ array_init_size(return_value, result);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for (i=0; i<result; i++) {
- add_next_index_long(return_value, gidlist[i]);
+ add_index_long(return_value, i, gidlist[i]);
}
efree(gidlist);
}
@@ -380,7 +381,7 @@ PHP_FUNCTION(posix_times)
RETURN_FALSE;
}
- array_init(return_value);
+ array_init_size(return_value, 5);
add_assoc_long(return_value, "ticks", ticks); /* clock ticks */
add_assoc_long(return_value, "utime", t.tms_utime); /* user time */
@@ -670,6 +671,7 @@ int php_posix_group_to_array(struct group *g, zval *array_group) /* {{{ */
return 0;
array_init(&array_members);
+ zend_hash_real_init_packed(Z_ARRVAL(array_members));
add_assoc_string(array_group, "name", g->gr_name);
if (g->gr_passwd) {
@@ -1174,7 +1176,8 @@ PHP_FUNCTION(posix_getrlimit)
RETURN_FALSE;
}
- array_init(return_value);
+ array_init_size(return_value, 2);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
if (rl.rlim_cur == RLIM_INFINITY) {
add_next_index_stringl(return_value, UNLIMITED_STRING, sizeof(UNLIMITED_STRING)-1);
} else {
| diff --git a/ext/posix/posix.c b/ext/posix/posix.c
index d465e5230938a..68d47840c5e20 100644
--- a/ext/posix/posix.c
+++ b/ext/posix/posix.c
@@ -236,10 +236,11 @@ PHP_FUNCTION(posix_getgroups)
+ array_init_size(return_value, result);
for (i=0; i<result; i++) {
+ add_index_long(return_value, i, gidlist[i]);
efree(gidlist);
}
@@ -380,7 +381,7 @@ PHP_FUNCTION(posix_times)
+ array_init_size(return_value, 5);
add_assoc_long(return_value, "ticks", ticks); /* clock ticks */
add_assoc_long(return_value, "utime", t.tms_utime); /* user time */
@@ -670,6 +671,7 @@ int php_posix_group_to_array(struct group *g, zval *array_group) /* {{{ */
return 0;
array_init(&array_members);
+ zend_hash_real_init_packed(Z_ARRVAL(array_members));
add_assoc_string(array_group, "name", g->gr_name);
if (g->gr_passwd) {
@@ -1174,7 +1176,8 @@ PHP_FUNCTION(posix_getrlimit)
RETURN_FALSE;
}
+ array_init_size(return_value, 2);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
if (rl.rlim_cur == RLIM_INFINITY) {
add_next_index_stringl(return_value, UNLIMITED_STRING, sizeof(UNLIMITED_STRING)-1);
} else { | [
"+\tzend_hash_real_init_packed(Z_ARRVAL_P(return_value));",
"-\t\tadd_next_index_long(return_value, gidlist[i]);",
"-\t\tarray_init(return_value);"
] | [
10,
13,
39
] | {
"additions": 7,
"author": "devnexen",
"deletions": 4,
"html_url": "https://github.com/php/php-src/pull/18370",
"issue_id": 18370,
"merged_at": "2025-04-20T22:23:43Z",
"omission_probability": 0.1,
"pr_number": 18370,
"repo": "php/php-src",
"title": "ext/posix: preallocate arrays and/or change to packed ones.",
"total_changes": 11
} |
747 | diff --git a/ext/gd/gd.c b/ext/gd/gd.c
index c993860f3b47..e993fb65f47d 100644
--- a/ext/gd/gd.c
+++ b/ext/gd/gd.c
@@ -2438,7 +2438,7 @@ PHP_FUNCTION(imagecolorsforindex)
col = index;
if ((col >= 0 && gdImageTrueColor(im)) || (!gdImageTrueColor(im) && col >= 0 && col < gdImageColorsTotal(im))) {
- array_init(return_value);
+ array_init_size(return_value, 4);
add_assoc_long(return_value,"red", gdImageRed(im,col));
add_assoc_long(return_value,"green", gdImageGreen(im,col));
@@ -3303,11 +3303,12 @@ PHP_FUNCTION(imagegetclip)
gdImageGetClip(im, &x1, &y1, &x2, &y2);
- array_init(return_value);
- add_next_index_long(return_value, x1);
- add_next_index_long(return_value, y1);
- add_next_index_long(return_value, x2);
- add_next_index_long(return_value, y2);
+ array_init_size(return_value, 4);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
+ add_index_long(return_value, 0, x1);
+ add_index_long(return_value, 1, y1);
+ add_index_long(return_value, 2, x2);
+ add_index_long(return_value, 3, y2);
}
/* }}} */
@@ -3398,11 +3399,12 @@ static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode)
RETURN_FALSE;
}
- array_init(return_value);
+ array_init_size(return_value, 8);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
/* return array with the text's bounding box */
for (i = 0; i < 8; i++) {
- add_next_index_long(return_value, brect[i]);
+ add_index_long(return_value, i, brect[i]);
}
}
/* }}} */
@@ -4130,7 +4132,8 @@ PHP_FUNCTION(imageaffinematrixget)
if (res == GD_FALSE) {
RETURN_FALSE;
} else {
- array_init(return_value);
+ array_init_size(return_value, 6);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for (uint8_t i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
@@ -4196,7 +4199,8 @@ PHP_FUNCTION(imageaffinematrixconcat)
RETURN_FALSE;
}
- array_init(return_value);
+ array_init_size(return_value, 6);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, mr[i]);
}
@@ -4288,9 +4292,10 @@ PHP_FUNCTION(imageresolution)
RETURN_TRUE;
}
- array_init(return_value);
- add_next_index_long(return_value, gdImageResolutionX(im));
- add_next_index_long(return_value, gdImageResolutionY(im));
+ zval imx, imy;
+ ZVAL_LONG(&imx, gdImageResolutionX(im));
+ ZVAL_LONG(&imy, gdImageResolutionY(im));
+ RETURN_ARR(zend_new_pair(&imx, &imy));
}
/* }}} */
| diff --git a/ext/gd/gd.c b/ext/gd/gd.c
index c993860f3b47..e993fb65f47d 100644
--- a/ext/gd/gd.c
+++ b/ext/gd/gd.c
@@ -2438,7 +2438,7 @@ PHP_FUNCTION(imagecolorsforindex)
col = index;
if ((col >= 0 && gdImageTrueColor(im)) || (!gdImageTrueColor(im) && col >= 0 && col < gdImageColorsTotal(im))) {
+ array_init_size(return_value, 4);
add_assoc_long(return_value,"red", gdImageRed(im,col));
add_assoc_long(return_value,"green", gdImageGreen(im,col));
@@ -3303,11 +3303,12 @@ PHP_FUNCTION(imagegetclip)
gdImageGetClip(im, &x1, &y1, &x2, &y2);
- add_next_index_long(return_value, x1);
- add_next_index_long(return_value, y1);
- add_next_index_long(return_value, y2);
+ array_init_size(return_value, 4);
+ add_index_long(return_value, 0, x1);
+ add_index_long(return_value, 1, y1);
+ add_index_long(return_value, 2, x2);
+ add_index_long(return_value, 3, y2);
@@ -3398,11 +3399,12 @@ static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode)
+ array_init_size(return_value, 8);
/* return array with the text's bounding box */
for (i = 0; i < 8; i++) {
- add_next_index_long(return_value, brect[i]);
+ add_index_long(return_value, i, brect[i]);
@@ -4130,7 +4132,8 @@ PHP_FUNCTION(imageaffinematrixget)
if (res == GD_FALSE) {
} else {
+ array_init_size(return_value, 6);
for (uint8_t i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
@@ -4196,7 +4199,8 @@ PHP_FUNCTION(imageaffinematrixconcat)
+ array_init_size(return_value, 6);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, mr[i]);
@@ -4288,9 +4292,10 @@ PHP_FUNCTION(imageresolution)
RETURN_TRUE;
- add_next_index_long(return_value, gdImageResolutionX(im));
- add_next_index_long(return_value, gdImageResolutionY(im));
+ zval imx, imy;
+ ZVAL_LONG(&imx, gdImageResolutionX(im));
+ ZVAL_LONG(&imy, gdImageResolutionY(im));
+ RETURN_ARR(zend_new_pair(&imx, &imy)); | [
"-\tadd_next_index_long(return_value, x2);",
"+\t\tzend_hash_real_init_packed(Z_ARRVAL_P(return_value));"
] | [
20,
52
] | {
"additions": 18,
"author": "devnexen",
"deletions": 13,
"html_url": "https://github.com/php/php-src/pull/18366",
"issue_id": 18366,
"merged_at": "2025-04-20T16:30:12Z",
"omission_probability": 0.1,
"pr_number": 18366,
"repo": "php/php-src",
"title": "ext/gd: array supplied to user optimisations.",
"total_changes": 31
} |
748 | diff --git a/ext/intl/collator/collator_sort.c b/ext/intl/collator/collator_sort.c
index c28ffb82cf737..75466aacb07af 100644
--- a/ext/intl/collator/collator_sort.c
+++ b/ext/intl/collator/collator_sort.c
@@ -469,7 +469,8 @@ PHP_FUNCTION( collator_sort_with_sort_keys )
ZVAL_COPY_VALUE(&garbage, array);
/* for resulting hash we'll assign new hash keys rather then reordering */
- array_init(array);
+ array_init_size(array, sortKeyCount);
+ zend_hash_real_init_packed(Z_ARRVAL_P(array));
for( j = 0; j < sortKeyCount; j++ )
{
diff --git a/ext/intl/converter/converter.c b/ext/intl/converter/converter.c
index 73a7cb573134a..3aa7a53aa485b 100644
--- a/ext/intl/converter/converter.c
+++ b/ext/intl/converter/converter.c
@@ -294,7 +294,8 @@ static void php_converter_from_u_callback(const void *context,
zval zargs[4];
ZVAL_LONG(&zargs[0], reason);
- array_init(&zargs[1]);
+ array_init_size(&zargs[1], length);
+ zend_hash_real_init_packed(Z_ARRVAL(zargs[1]));
int i = 0;
while (i < length) {
UChar32 c;
@@ -807,7 +808,8 @@ PHP_METHOD(UConverter, getAvailable) {
intl_error_reset(NULL);
- array_init(return_value);
+ array_init_size(return_value, count);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for(i = 0; i < count; i++) {
const char *name = ucnv_getAvailableName(i);
add_next_index_string(return_value, name);
@@ -833,7 +835,8 @@ PHP_METHOD(UConverter, getAliases) {
RETURN_FALSE;
}
- array_init(return_value);
+ array_init_size(return_value, count);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for(i = 0; i < count; i++) {
const char *alias;
@@ -856,8 +859,9 @@ PHP_METHOD(UConverter, getStandards) {
ZEND_PARSE_PARAMETERS_NONE();
intl_error_reset(NULL);
- array_init(return_value);
count = ucnv_countStandards();
+ array_init_size(return_value, count);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for(i = 0; i < count; i++) {
UErrorCode error = U_ZERO_ERROR;
const char *name = ucnv_getStandard(i, &error);
diff --git a/ext/intl/msgformat/msgformat_parse.c b/ext/intl/msgformat/msgformat_parse.c
index c55671cf856a6..80ede995c42e7 100644
--- a/ext/intl/msgformat/msgformat_parse.c
+++ b/ext/intl/msgformat/msgformat_parse.c
@@ -42,7 +42,8 @@ static void msgfmt_do_parse(MessageFormatter_object *mfo, char *source, size_t s
}
INTL_METHOD_CHECK_STATUS(mfo, "Parsing failed");
- array_init(return_value);
+ array_init_size(return_value, count);
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for(i=0;i<count;i++) {
add_next_index_zval(return_value, &fargs[i]);
}
diff --git a/ext/intl/resourcebundle/resourcebundle.c b/ext/intl/resourcebundle/resourcebundle.c
index 5535ddd29a6b7..e29596f01872e 100644
--- a/ext/intl/resourcebundle/resourcebundle.c
+++ b/ext/intl/resourcebundle/resourcebundle.c
@@ -57,7 +57,8 @@ void resourcebundle_extract_value( zval *return_value, ResourceBundle_object *so
case URES_INT_VECTOR:
vfield = ures_getIntVector( source->child, &ilen, &INTL_DATA_ERROR_CODE(source) );
INTL_METHOD_CHECK_STATUS(source, "Failed to retrieve vector value");
- array_init( return_value );
+ array_init_size( return_value, ilen );
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for (i=0; i<ilen; i++) {
add_next_index_long( return_value, vfield[i] );
}
| diff --git a/ext/intl/collator/collator_sort.c b/ext/intl/collator/collator_sort.c
index c28ffb82cf737..75466aacb07af 100644
--- a/ext/intl/collator/collator_sort.c
+++ b/ext/intl/collator/collator_sort.c
@@ -469,7 +469,8 @@ PHP_FUNCTION( collator_sort_with_sort_keys )
ZVAL_COPY_VALUE(&garbage, array);
/* for resulting hash we'll assign new hash keys rather then reordering */
- array_init(array);
+ array_init_size(array, sortKeyCount);
+ zend_hash_real_init_packed(Z_ARRVAL_P(array));
for( j = 0; j < sortKeyCount; j++ )
{
diff --git a/ext/intl/converter/converter.c b/ext/intl/converter/converter.c
index 73a7cb573134a..3aa7a53aa485b 100644
--- a/ext/intl/converter/converter.c
+++ b/ext/intl/converter/converter.c
@@ -294,7 +294,8 @@ static void php_converter_from_u_callback(const void *context,
zval zargs[4];
ZVAL_LONG(&zargs[0], reason);
- array_init(&zargs[1]);
+ array_init_size(&zargs[1], length);
+ zend_hash_real_init_packed(Z_ARRVAL(zargs[1]));
int i = 0;
while (i < length) {
UChar32 c;
@@ -807,7 +808,8 @@ PHP_METHOD(UConverter, getAvailable) {
const char *name = ucnv_getAvailableName(i);
add_next_index_string(return_value, name);
@@ -833,7 +835,8 @@ PHP_METHOD(UConverter, getAliases) {
RETURN_FALSE;
const char *alias;
@@ -856,8 +859,9 @@ PHP_METHOD(UConverter, getStandards) {
ZEND_PARSE_PARAMETERS_NONE();
count = ucnv_countStandards();
UErrorCode error = U_ZERO_ERROR;
const char *name = ucnv_getStandard(i, &error);
diff --git a/ext/intl/msgformat/msgformat_parse.c b/ext/intl/msgformat/msgformat_parse.c
index c55671cf856a6..80ede995c42e7 100644
--- a/ext/intl/msgformat/msgformat_parse.c
+++ b/ext/intl/msgformat/msgformat_parse.c
@@ -42,7 +42,8 @@ static void msgfmt_do_parse(MessageFormatter_object *mfo, char *source, size_t s
INTL_METHOD_CHECK_STATUS(mfo, "Parsing failed");
for(i=0;i<count;i++) {
add_next_index_zval(return_value, &fargs[i]);
diff --git a/ext/intl/resourcebundle/resourcebundle.c b/ext/intl/resourcebundle/resourcebundle.c
index 5535ddd29a6b7..e29596f01872e 100644
--- a/ext/intl/resourcebundle/resourcebundle.c
+++ b/ext/intl/resourcebundle/resourcebundle.c
@@ -57,7 +57,8 @@ void resourcebundle_extract_value( zval *return_value, ResourceBundle_object *so
case URES_INT_VECTOR:
vfield = ures_getIntVector( source->child, &ilen, &INTL_DATA_ERROR_CODE(source) );
INTL_METHOD_CHECK_STATUS(source, "Failed to retrieve vector value");
- array_init( return_value );
+ array_init_size( return_value, ilen );
+ zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
for (i=0; i<ilen; i++) {
add_next_index_long( return_value, vfield[i] );
} | [] | [] | {
"additions": 14,
"author": "nielsdos",
"deletions": 7,
"html_url": "https://github.com/php/php-src/pull/18359",
"issue_id": 18359,
"merged_at": "2025-04-20T10:18:15Z",
"omission_probability": 0.1,
"pr_number": 18359,
"repo": "php/php-src",
"title": "Use pre-allocated array sizes and packed where possible in intl",
"total_changes": 21
} |
749 | diff --git a/ext/intl/idn/idn.c b/ext/intl/idn/idn.c
index 62ee83f62f9ba..cd4546ad7f8bb 100644
--- a/ext/intl/idn/idn.c
+++ b/ext/intl/idn/idn.c
@@ -57,6 +57,7 @@ static void php_intl_idn_to_46(INTERNAL_FUNCTION_PARAMETERS,
UErrorCode status = U_ZERO_ERROR;
UIDNA *uts46;
int32_t len;
+ int32_t buffer_capac;
zend_string *buffer;
UIDNAInfo info = UIDNA_INFO_INITIALIZER;
@@ -66,36 +67,25 @@ static void php_intl_idn_to_46(INTERNAL_FUNCTION_PARAMETERS,
}
if (mode == INTL_IDN_TO_ASCII) {
- const int32_t buffer_capac = 255;
+ buffer_capac = 255;
buffer = zend_string_alloc(buffer_capac, 0);
len = uidna_nameToASCII_UTF8(uts46, ZSTR_VAL(domain), ZSTR_LEN(domain),
ZSTR_VAL(buffer), buffer_capac, &info, &status);
- if (len >= buffer_capac || php_intl_idn_check_status(status, "failed to convert name") == FAILURE) {
- uidna_close(uts46);
- zend_string_efree(buffer);
- RETURN_FALSE;
- }
} else {
- const int32_t buffer_capac = 252*4;
+ buffer_capac = 252*4;
buffer = zend_string_alloc(buffer_capac, 0);
len = uidna_nameToUnicodeUTF8(uts46, ZSTR_VAL(domain), ZSTR_LEN(domain),
ZSTR_VAL(buffer), buffer_capac, &info, &status);
- if (len >= buffer_capac || php_intl_idn_check_status(status, "failed to convert name") == FAILURE) {
- uidna_close(uts46);
- zend_string_efree(buffer);
- RETURN_FALSE;
- }
+ }
+ if (len >= buffer_capac || php_intl_idn_check_status(status, "failed to convert name") == FAILURE) {
+ uidna_close(uts46);
+ zend_string_efree(buffer);
+ RETURN_FALSE;
}
ZSTR_VAL(buffer)[len] = '\0';
ZSTR_LEN(buffer) = len;
- if (info.errors == 0) {
- RETVAL_STR_COPY(buffer);
- } else {
- RETVAL_FALSE;
- }
-
if (idna_info) {
add_assoc_str_ex(idna_info, "result", sizeof("result")-1, zend_string_copy(buffer));
add_assoc_bool_ex(idna_info, "isTransitionalDifferent",
@@ -103,7 +93,13 @@ static void php_intl_idn_to_46(INTERNAL_FUNCTION_PARAMETERS,
add_assoc_long_ex(idna_info, "errors", sizeof("errors")-1, (zend_long)info.errors);
}
- zend_string_release(buffer);
+ if (info.errors == 0) {
+ RETVAL_STR(buffer);
+ } else {
+ zend_string_release_ex(buffer, false);
+ RETVAL_FALSE;
+ }
+
uidna_close(uts46);
}
| diff --git a/ext/intl/idn/idn.c b/ext/intl/idn/idn.c
index 62ee83f62f9ba..cd4546ad7f8bb 100644
--- a/ext/intl/idn/idn.c
+++ b/ext/intl/idn/idn.c
@@ -57,6 +57,7 @@ static void php_intl_idn_to_46(INTERNAL_FUNCTION_PARAMETERS,
UErrorCode status = U_ZERO_ERROR;
UIDNA *uts46;
int32_t len;
+ int32_t buffer_capac;
zend_string *buffer;
UIDNAInfo info = UIDNA_INFO_INITIALIZER;
@@ -66,36 +67,25 @@ static void php_intl_idn_to_46(INTERNAL_FUNCTION_PARAMETERS,
if (mode == INTL_IDN_TO_ASCII) {
- const int32_t buffer_capac = 255;
+ buffer_capac = 255;
len = uidna_nameToASCII_UTF8(uts46, ZSTR_VAL(domain), ZSTR_LEN(domain),
} else {
- const int32_t buffer_capac = 252*4;
+ buffer_capac = 252*4;
len = uidna_nameToUnicodeUTF8(uts46, ZSTR_VAL(domain), ZSTR_LEN(domain),
+ if (len >= buffer_capac || php_intl_idn_check_status(status, "failed to convert name") == FAILURE) {
+ uidna_close(uts46);
+ zend_string_efree(buffer);
+ RETURN_FALSE;
ZSTR_VAL(buffer)[len] = '\0';
ZSTR_LEN(buffer) = len;
- if (info.errors == 0) {
- RETVAL_STR_COPY(buffer);
- } else {
- RETVAL_FALSE;
- }
-
if (idna_info) {
add_assoc_str_ex(idna_info, "result", sizeof("result")-1, zend_string_copy(buffer));
add_assoc_bool_ex(idna_info, "isTransitionalDifferent",
@@ -103,7 +93,13 @@ static void php_intl_idn_to_46(INTERNAL_FUNCTION_PARAMETERS,
add_assoc_long_ex(idna_info, "errors", sizeof("errors")-1, (zend_long)info.errors);
- zend_string_release(buffer);
+ if (info.errors == 0) {
+ RETVAL_STR(buffer);
+ } else {
+ zend_string_release_ex(buffer, false);
+ RETVAL_FALSE;
uidna_close(uts46);
} | [
"+"
] | [
67
] | {
"additions": 15,
"author": "nielsdos",
"deletions": 19,
"html_url": "https://github.com/php/php-src/pull/18360",
"issue_id": 18360,
"merged_at": "2025-04-20T10:17:50Z",
"omission_probability": 0.1,
"pr_number": 18360,
"repo": "php/php-src",
"title": "Cleanup in intl/idn",
"total_changes": 34
} |
750 | diff --git a/ext/dom/dom_iterators.c b/ext/dom/dom_iterators.c
index e292728de271..a0797967d1e7 100644
--- a/ext/dom/dom_iterators.c
+++ b/ext/dom/dom_iterators.c
@@ -189,9 +189,8 @@ static void php_dom_iterator_move_forward(zend_object_iterator *iter) /* {{{ */
objmap->nodetype != XML_NOTATION_NODE) {
if (objmap->nodetype == DOM_NODESET) {
HashTable *nodeht = Z_ARRVAL_P(&objmap->baseobj_zv);
- zval *entry;
- zend_hash_move_forward_ex(nodeht, &iterator->pos);
- if ((entry = zend_hash_get_current_data_ex(nodeht, &iterator->pos))) {
+ zval *entry = zend_hash_index_find(nodeht, iterator->index);
+ if (entry) {
zval_ptr_dtor(&iterator->curobj);
ZVAL_COPY(&iterator->curobj, entry);
return;
@@ -263,8 +262,6 @@ zend_object_iterator *php_dom_get_iterator(zend_class_entry *ce, zval *object, i
dom_object *intern;
dom_nnodemap_object *objmap;
xmlNodePtr curnode=NULL;
- HashTable *nodeht;
- zval *entry;
php_dom_iterator *iterator;
if (by_ref) {
@@ -284,9 +281,9 @@ zend_object_iterator *php_dom_get_iterator(zend_class_entry *ce, zval *object, i
if (objmap->nodetype != XML_ENTITY_NODE &&
objmap->nodetype != XML_NOTATION_NODE) {
if (objmap->nodetype == DOM_NODESET) {
- nodeht = Z_ARRVAL_P(&objmap->baseobj_zv);
- zend_hash_internal_pointer_reset_ex(nodeht, &iterator->pos);
- if ((entry = zend_hash_get_current_data_ex(nodeht, &iterator->pos))) {
+ HashTable *nodeht = Z_ARRVAL_P(&objmap->baseobj_zv);
+ zval *entry = zend_hash_index_find(nodeht, 0);
+ if (entry) {
ZVAL_COPY(&iterator->curobj, entry);
}
} else {
diff --git a/ext/dom/php_dom.h b/ext/dom/php_dom.h
index 438857305db6..31fec5a7cabc 100644
--- a/ext/dom/php_dom.h
+++ b/ext/dom/php_dom.h
@@ -97,7 +97,6 @@ typedef struct dom_nnodemap_object {
typedef struct {
zend_object_iterator intern;
zval curobj;
- HashPosition pos;
/* intern->index is only updated for FE_* opcodes, not for e.g. unpacking,
* yet we need to track the position of the node relative to the start. */
zend_ulong index;
| diff --git a/ext/dom/dom_iterators.c b/ext/dom/dom_iterators.c
index e292728de271..a0797967d1e7 100644
--- a/ext/dom/dom_iterators.c
+++ b/ext/dom/dom_iterators.c
@@ -189,9 +189,8 @@ static void php_dom_iterator_move_forward(zend_object_iterator *iter) /* {{{ */
HashTable *nodeht = Z_ARRVAL_P(&objmap->baseobj_zv);
- zval *entry;
- zend_hash_move_forward_ex(nodeht, &iterator->pos);
+ zval *entry = zend_hash_index_find(nodeht, iterator->index);
zval_ptr_dtor(&iterator->curobj);
return;
@@ -263,8 +262,6 @@ zend_object_iterator *php_dom_get_iterator(zend_class_entry *ce, zval *object, i
dom_object *intern;
dom_nnodemap_object *objmap;
xmlNodePtr curnode=NULL;
- HashTable *nodeht;
- zval *entry;
php_dom_iterator *iterator;
if (by_ref) {
@@ -284,9 +281,9 @@ zend_object_iterator *php_dom_get_iterator(zend_class_entry *ce, zval *object, i
if (objmap->nodetype != XML_ENTITY_NODE &&
- nodeht = Z_ARRVAL_P(&objmap->baseobj_zv);
- zend_hash_internal_pointer_reset_ex(nodeht, &iterator->pos);
+ HashTable *nodeht = Z_ARRVAL_P(&objmap->baseobj_zv);
+ zval *entry = zend_hash_index_find(nodeht, 0);
}
} else {
diff --git a/ext/dom/php_dom.h b/ext/dom/php_dom.h
index 438857305db6..31fec5a7cabc 100644
--- a/ext/dom/php_dom.h
+++ b/ext/dom/php_dom.h
@@ -97,7 +97,6 @@ typedef struct dom_nnodemap_object {
typedef struct {
zend_object_iterator intern;
zval curobj;
- HashPosition pos;
/* intern->index is only updated for FE_* opcodes, not for e.g. unpacking,
* yet we need to track the position of the node relative to the start. */
zend_ulong index; | [] | [] | {
"additions": 5,
"author": "nielsdos",
"deletions": 9,
"html_url": "https://github.com/php/php-src/pull/18354",
"issue_id": 18354,
"merged_at": "2025-04-19T15:59:48Z",
"omission_probability": 0.1,
"pr_number": 18354,
"repo": "php/php-src",
"title": "Get rid of separate DOM HashPosition member",
"total_changes": 14
} |
751 | diff --git a/ext/mysqlnd/mysqlnd_auth.c b/ext/mysqlnd/mysqlnd_auth.c
index 3a30b1458dea0..b8a23f87c663e 100644
--- a/ext/mysqlnd/mysqlnd_auth.c
+++ b/ext/mysqlnd/mysqlnd_auth.c
@@ -487,10 +487,6 @@ mysqlnd_auth_change_user(MYSQLND_CONN_DATA * const conn,
}
}
if (ret == PASS) {
- ZEND_ASSERT(conn->username.s != user && conn->password.s != passwd);
- mysqlnd_set_persistent_string(&conn->username, user, user_len, conn->persistent);
- mysqlnd_set_persistent_string(&conn->password, passwd, passwd_len, conn->persistent);
-
mysqlnd_set_string(&conn->last_message, NULL, 0);
UPSERT_STATUS_RESET(conn->upsert_status);
/* set charset for old servers */
diff --git a/ext/mysqlnd/mysqlnd_commands.c b/ext/mysqlnd/mysqlnd_commands.c
index 27a5f13a30746..52731425e1808 100644
--- a/ext/mysqlnd/mysqlnd_commands.c
+++ b/ext/mysqlnd/mysqlnd_commands.c
@@ -107,9 +107,6 @@ MYSQLND_METHOD(mysqlnd_command, init_db)(MYSQLND_CONN_DATA * const conn, const M
a protocol of giving back -1. Thus we have to follow it :(
*/
UPSERT_STATUS_SET_AFFECTED_ROWS_TO_ERROR(conn->upsert_status);
- if (ret == PASS) {
- mysqlnd_set_persistent_string(&conn->connect_or_select_db, db.s, db.l, conn->persistent);
- }
DBG_RETURN(ret);
}
diff --git a/ext/mysqlnd/mysqlnd_connection.c b/ext/mysqlnd/mysqlnd_connection.c
index 2787b32931747..42acb258665bc 100644
--- a/ext/mysqlnd/mysqlnd_connection.c
+++ b/ext/mysqlnd/mysqlnd_connection.c
@@ -282,11 +282,6 @@ MYSQLND_METHOD(mysqlnd_conn_data, free_contents)(MYSQLND_CONN_DATA * conn)
DBG_INF("Freeing memory of members");
- mysqlnd_set_persistent_string(&conn->hostname, NULL, 0, pers);
- mysqlnd_set_persistent_string(&conn->username, NULL, 0, pers);
- mysqlnd_set_persistent_string(&conn->password, NULL, 0, pers);
- mysqlnd_set_persistent_string(&conn->connect_or_select_db, NULL, 0, pers);
- mysqlnd_set_persistent_string(&conn->unix_socket, NULL, 0, pers);
DBG_INF_FMT("scheme=%s", conn->scheme.s);
mysqlnd_set_persistent_string(&conn->scheme, NULL, 0, pers);
@@ -658,22 +653,16 @@ MYSQLND_METHOD(mysqlnd_conn_data, connect)(MYSQLND_CONN_DATA * conn,
if (transport.s) {
mnd_sprintf_free(transport.s);
transport.s = NULL;
- }
-
- if (!conn->scheme.s) {
+ } else {
goto err; /* OOM */
}
- mysqlnd_set_persistent_string(&conn->username, username.s, username.l, conn->persistent);
- mysqlnd_set_persistent_string(&conn->password, username.s, password.l, conn->persistent);
conn->port = port;
- mysqlnd_set_persistent_string(&conn->connect_or_select_db, database.s, database.l, conn->persistent);
if (!unix_socket && !named_pipe) {
- mysqlnd_set_persistent_string(&conn->hostname, hostname.s, hostname.l, conn->persistent);
{
char *p;
- mnd_sprintf(&p, 0, "%s via TCP/IP", conn->hostname.s);
+ mnd_sprintf(&p, 0, "%s via TCP/IP", hostname.s);
if (!p) {
SET_OOM_ERROR(conn->error_info);
goto err; /* OOM */
@@ -682,12 +671,11 @@ MYSQLND_METHOD(mysqlnd_conn_data, connect)(MYSQLND_CONN_DATA * conn,
mnd_sprintf_free(p);
}
} else {
- conn->unix_socket.s = mnd_pestrdup(socket_or_pipe.s, conn->persistent);
if (unix_socket) {
conn->host_info = mnd_pestrdup("Localhost via UNIX socket", conn->persistent);
} else if (named_pipe) {
char *p;
- mnd_sprintf(&p, 0, "%s via named pipe", conn->unix_socket.s);
+ mnd_sprintf(&p, 0, "%s via named pipe", socket_or_pipe.s);
if (!p) {
SET_OOM_ERROR(conn->error_info);
goto err; /* OOM */
@@ -697,11 +685,10 @@ MYSQLND_METHOD(mysqlnd_conn_data, connect)(MYSQLND_CONN_DATA * conn,
} else {
php_error_docref(NULL, E_WARNING, "Impossible. Should be either socket or a pipe. Report a bug!");
}
- if (!conn->unix_socket.s || !conn->host_info) {
+ if (!socket_or_pipe.s || !conn->host_info) {
SET_OOM_ERROR(conn->error_info);
goto err; /* OOM */
}
- conn->unix_socket.l = strlen(conn->unix_socket.s);
}
SET_EMPTY_ERROR(conn->error_info);
diff --git a/ext/mysqlnd/mysqlnd_structs.h b/ext/mysqlnd/mysqlnd_structs.h
index cf99ac706239c..f0722f578d504 100644
--- a/ext/mysqlnd/mysqlnd_structs.h
+++ b/ext/mysqlnd/mysqlnd_structs.h
@@ -890,10 +890,6 @@ struct st_mysqlnd_connection_data
MYSQLND_PROTOCOL_PAYLOAD_DECODER_FACTORY * payload_decoder_factory;
/* Information related */
- MYSQLND_STRING hostname;
- MYSQLND_STRING unix_socket;
- MYSQLND_STRING username;
- MYSQLND_STRING password;
MYSQLND_STRING scheme;
uint64_t thread_id;
char *server_version;
@@ -901,7 +897,6 @@ struct st_mysqlnd_connection_data
MYSQLND_STRING authentication_plugin_data;
const MYSQLND_CHARSET *charset;
const MYSQLND_CHARSET *greet_charset;
- MYSQLND_STRING connect_or_select_db;
MYSQLND_INFILE infile;
unsigned int protocol_version;
unsigned int port;
| diff --git a/ext/mysqlnd/mysqlnd_auth.c b/ext/mysqlnd/mysqlnd_auth.c
index 3a30b1458dea0..b8a23f87c663e 100644
--- a/ext/mysqlnd/mysqlnd_auth.c
+++ b/ext/mysqlnd/mysqlnd_auth.c
@@ -487,10 +487,6 @@ mysqlnd_auth_change_user(MYSQLND_CONN_DATA * const conn,
}
if (ret == PASS) {
- ZEND_ASSERT(conn->username.s != user && conn->password.s != passwd);
- mysqlnd_set_persistent_string(&conn->username, user, user_len, conn->persistent);
- mysqlnd_set_persistent_string(&conn->password, passwd, passwd_len, conn->persistent);
mysqlnd_set_string(&conn->last_message, NULL, 0);
UPSERT_STATUS_RESET(conn->upsert_status);
/* set charset for old servers */
diff --git a/ext/mysqlnd/mysqlnd_commands.c b/ext/mysqlnd/mysqlnd_commands.c
index 27a5f13a30746..52731425e1808 100644
--- a/ext/mysqlnd/mysqlnd_commands.c
+++ b/ext/mysqlnd/mysqlnd_commands.c
@@ -107,9 +107,6 @@ MYSQLND_METHOD(mysqlnd_command, init_db)(MYSQLND_CONN_DATA * const conn, const M
a protocol of giving back -1. Thus we have to follow it :(
*/
UPSERT_STATUS_SET_AFFECTED_ROWS_TO_ERROR(conn->upsert_status);
- if (ret == PASS) {
- mysqlnd_set_persistent_string(&conn->connect_or_select_db, db.s, db.l, conn->persistent);
- }
DBG_RETURN(ret);
}
diff --git a/ext/mysqlnd/mysqlnd_connection.c b/ext/mysqlnd/mysqlnd_connection.c
index 2787b32931747..42acb258665bc 100644
--- a/ext/mysqlnd/mysqlnd_connection.c
+++ b/ext/mysqlnd/mysqlnd_connection.c
@@ -282,11 +282,6 @@ MYSQLND_METHOD(mysqlnd_conn_data, free_contents)(MYSQLND_CONN_DATA * conn)
DBG_INF("Freeing memory of members");
- mysqlnd_set_persistent_string(&conn->hostname, NULL, 0, pers);
- mysqlnd_set_persistent_string(&conn->username, NULL, 0, pers);
- mysqlnd_set_persistent_string(&conn->password, NULL, 0, pers);
- mysqlnd_set_persistent_string(&conn->connect_or_select_db, NULL, 0, pers);
- mysqlnd_set_persistent_string(&conn->unix_socket, NULL, 0, pers);
DBG_INF_FMT("scheme=%s", conn->scheme.s);
mysqlnd_set_persistent_string(&conn->scheme, NULL, 0, pers);
@@ -658,22 +653,16 @@ MYSQLND_METHOD(mysqlnd_conn_data, connect)(MYSQLND_CONN_DATA * conn,
if (transport.s) {
mnd_sprintf_free(transport.s);
transport.s = NULL;
- }
- if (!conn->scheme.s) {
goto err; /* OOM */
- mysqlnd_set_persistent_string(&conn->username, username.s, username.l, conn->persistent);
- mysqlnd_set_persistent_string(&conn->password, username.s, password.l, conn->persistent);
conn->port = port;
- mysqlnd_set_persistent_string(&conn->connect_or_select_db, database.s, database.l, conn->persistent);
if (!unix_socket && !named_pipe) {
{
- mnd_sprintf(&p, 0, "%s via TCP/IP", conn->hostname.s);
+ mnd_sprintf(&p, 0, "%s via TCP/IP", hostname.s);
@@ -682,12 +671,11 @@ MYSQLND_METHOD(mysqlnd_conn_data, connect)(MYSQLND_CONN_DATA * conn,
mnd_sprintf_free(p);
} else {
- conn->unix_socket.s = mnd_pestrdup(socket_or_pipe.s, conn->persistent);
if (unix_socket) {
conn->host_info = mnd_pestrdup("Localhost via UNIX socket", conn->persistent);
} else if (named_pipe) {
- mnd_sprintf(&p, 0, "%s via named pipe", conn->unix_socket.s);
+ mnd_sprintf(&p, 0, "%s via named pipe", socket_or_pipe.s);
@@ -697,11 +685,10 @@ MYSQLND_METHOD(mysqlnd_conn_data, connect)(MYSQLND_CONN_DATA * conn,
} else {
php_error_docref(NULL, E_WARNING, "Impossible. Should be either socket or a pipe. Report a bug!");
- if (!conn->unix_socket.s || !conn->host_info) {
SET_OOM_ERROR(conn->error_info);
goto err; /* OOM */
- conn->unix_socket.l = strlen(conn->unix_socket.s);
SET_EMPTY_ERROR(conn->error_info);
diff --git a/ext/mysqlnd/mysqlnd_structs.h b/ext/mysqlnd/mysqlnd_structs.h
index cf99ac706239c..f0722f578d504 100644
--- a/ext/mysqlnd/mysqlnd_structs.h
+++ b/ext/mysqlnd/mysqlnd_structs.h
@@ -890,10 +890,6 @@ struct st_mysqlnd_connection_data
MYSQLND_PROTOCOL_PAYLOAD_DECODER_FACTORY * payload_decoder_factory;
/* Information related */
- MYSQLND_STRING hostname;
- MYSQLND_STRING unix_socket;
- MYSQLND_STRING username;
- MYSQLND_STRING password;
MYSQLND_STRING scheme;
uint64_t thread_id;
char *server_version;
@@ -901,7 +897,6 @@ struct st_mysqlnd_connection_data
MYSQLND_STRING authentication_plugin_data;
const MYSQLND_CHARSET *charset;
const MYSQLND_CHARSET *greet_charset;
- MYSQLND_STRING connect_or_select_db;
MYSQLND_INFILE infile;
unsigned int protocol_version;
unsigned int port; | [
"+\t\t} else {",
"-\t\t\tmysqlnd_set_persistent_string(&conn->hostname, hostname.s, hostname.l, conn->persistent);",
"+\t\t\tif (!socket_or_pipe.s || !conn->host_info) {"
] | [
52,
62,
89
] | {
"additions": 4,
"author": "kamil-tekiela",
"deletions": 29,
"html_url": "https://github.com/php/php-src/pull/18023",
"issue_id": 18023,
"merged_at": "2025-04-19T12:26:09Z",
"omission_probability": 0.1,
"pr_number": 18023,
"repo": "php/php-src",
"title": "Drop unused variables",
"total_changes": 33
} |
752 | diff --git a/ext/standard/exec.c b/ext/standard/exec.c
index 1df46cc050b01..ce3e8565ad200 100644
--- a/ext/standard/exec.c
+++ b/ext/standard/exec.c
@@ -118,7 +118,7 @@ PHPAPI int php_exec(int type, const char *cmd, zval *array, zval *return_value)
php_stream *stream;
size_t buflen, bufl = 0;
#if PHP_SIGCHILD
- void (*sig_handler)() = signal(SIGCHLD, SIG_DFL);
+ void (*sig_handler)(int) = signal(SIGCHLD, SIG_DFL);
#endif
#ifdef PHP_WIN32
diff --git a/ext/standard/mail.c b/ext/standard/mail.c
index 35c23a0be76c0..0243ec897a05e 100644
--- a/ext/standard/mail.c
+++ b/ext/standard/mail.c
@@ -445,7 +445,7 @@ PHPAPI bool php_mail(const char *to, const char *subject, const char *message, c
const char *hdr = headers;
char *ahdr = NULL;
#if PHP_SIGCHILD
- void (*sig_handler)() = NULL;
+ void (*sig_handler)(int) = NULL;
#endif
#define MAIL_RET(val) \
diff --git a/sapi/litespeed/lsapi_main.c b/sapi/litespeed/lsapi_main.c
index 259d4a985cc66..a135e031b24d0 100644
--- a/sapi/litespeed/lsapi_main.c
+++ b/sapi/litespeed/lsapi_main.c
@@ -1678,11 +1678,11 @@ PHP_FUNCTION(litespeed_response_headers)
char headerBuf[SAPI_LSAPI_MAX_HEADER_LENGTH];
if (zend_parse_parameters_none() == FAILURE) {
- RETURN_THROWS();
- }
+ RETURN_THROWS();
+ }
- if (!&SG(sapi_headers).headers) {
- RETURN_FALSE;
+ if (!zend_llist_count(&SG(sapi_headers).headers)) {
+ RETURN_FALSE;
}
array_init(return_value);
diff --git a/sapi/litespeed/lscriu.c b/sapi/litespeed/lscriu.c
index 1eb468fdf28cc..409fe989b5551 100644
--- a/sapi/litespeed/lscriu.c
+++ b/sapi/litespeed/lscriu.c
@@ -658,7 +658,7 @@ static int LSCRIU_Init_Env_Parameters(void)
}
-void LSCRIU_inc_req_processed()
+void LSCRIU_inc_req_processed(void)
{
if (!LSCRIU_Get_Global_Counter_Type()) {
++s_requests_count;
| diff --git a/ext/standard/exec.c b/ext/standard/exec.c
index 1df46cc050b01..ce3e8565ad200 100644
--- a/ext/standard/exec.c
+++ b/ext/standard/exec.c
@@ -118,7 +118,7 @@ PHPAPI int php_exec(int type, const char *cmd, zval *array, zval *return_value)
php_stream *stream;
size_t buflen, bufl = 0;
+ void (*sig_handler)(int) = signal(SIGCHLD, SIG_DFL);
#ifdef PHP_WIN32
diff --git a/ext/standard/mail.c b/ext/standard/mail.c
index 35c23a0be76c0..0243ec897a05e 100644
--- a/ext/standard/mail.c
+++ b/ext/standard/mail.c
@@ -445,7 +445,7 @@ PHPAPI bool php_mail(const char *to, const char *subject, const char *message, c
const char *hdr = headers;
char *ahdr = NULL;
#define MAIL_RET(val) \
diff --git a/sapi/litespeed/lsapi_main.c b/sapi/litespeed/lsapi_main.c
index 259d4a985cc66..a135e031b24d0 100644
--- a/sapi/litespeed/lsapi_main.c
+++ b/sapi/litespeed/lsapi_main.c
@@ -1678,11 +1678,11 @@ PHP_FUNCTION(litespeed_response_headers)
char headerBuf[SAPI_LSAPI_MAX_HEADER_LENGTH];
if (zend_parse_parameters_none() == FAILURE) {
- RETURN_THROWS();
+ RETURN_THROWS();
+ }
- if (!&SG(sapi_headers).headers) {
- RETURN_FALSE;
+ if (!zend_llist_count(&SG(sapi_headers).headers)) {
}
array_init(return_value);
diff --git a/sapi/litespeed/lscriu.c b/sapi/litespeed/lscriu.c
index 1eb468fdf28cc..409fe989b5551 100644
--- a/sapi/litespeed/lscriu.c
+++ b/sapi/litespeed/lscriu.c
@@ -658,7 +658,7 @@ static int LSCRIU_Init_Env_Parameters(void)
}
-void LSCRIU_inc_req_processed()
+void LSCRIU_inc_req_processed(void)
{
if (!LSCRIU_Get_Global_Counter_Type()) {
++s_requests_count; | [
"-\tvoid (*sig_handler)() = signal(SIGCHLD, SIG_DFL);",
"-\tvoid (*sig_handler)() = NULL;",
"+\tvoid (*sig_handler)(int) = NULL;",
"-\t}",
"+\t RETURN_FALSE;"
] | [
8,
21,
22,
35,
42
] | {
"additions": 7,
"author": "devnexen",
"deletions": 7,
"html_url": "https://github.com/php/php-src/pull/18265",
"issue_id": 18265,
"merged_at": "2025-04-19T09:18:53Z",
"omission_probability": 0.1,
"pr_number": 18265,
"repo": "php/php-src",
"title": "Fix few build warnings.",
"total_changes": 14
} |
753 | diff --git a/ext/standard/array.c b/ext/standard/array.c
index 4ab3a690120b..cabb43d8a914 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -6439,7 +6439,7 @@ PHP_FUNCTION(array_reduce)
zval args[2];
zval *operand;
zend_fcall_info fci;
- zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
+ zend_fcall_info_cache fci_cache;
zval *initial = NULL;
HashTable *htbl;
@@ -6515,7 +6515,7 @@ PHP_FUNCTION(array_filter)
zend_long use_type = 0;
zend_string *string_key;
zend_fcall_info fci = empty_fcall_info;
- zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
+ zend_fcall_info_cache fci_cache;
zend_ulong num_key;
ZEND_PARSE_PARAMETERS_START(1, 3)
@@ -6649,7 +6649,7 @@ PHP_FUNCTION(array_find)
{
HashTable *array;
zend_fcall_info fci;
- zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
+ zend_fcall_info_cache fci_cache;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ARRAY_HT(array)
@@ -6665,7 +6665,7 @@ PHP_FUNCTION(array_find_key)
{
HashTable *array;
zend_fcall_info fci;
- zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
+ zend_fcall_info_cache fci_cache;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ARRAY_HT(array)
@@ -6681,7 +6681,7 @@ PHP_FUNCTION(array_any)
{
HashTable *array;
zend_fcall_info fci;
- zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
+ zend_fcall_info_cache fci_cache;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ARRAY_HT(array)
@@ -6697,7 +6697,7 @@ PHP_FUNCTION(array_all)
{
HashTable *array;
zend_fcall_info fci;
- zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
+ zend_fcall_info_cache fci_cache;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ARRAY_HT(array)
@@ -6714,8 +6714,8 @@ PHP_FUNCTION(array_map)
zval *arrays = NULL;
int n_arrays = 0;
zval result;
- zend_fcall_info fci = empty_fcall_info;
- zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
+ zend_fcall_info fci;
+ zend_fcall_info_cache fci_cache;
int i;
uint32_t k, maxlen = 0;
| diff --git a/ext/standard/array.c b/ext/standard/array.c
index 4ab3a690120b..cabb43d8a914 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -6439,7 +6439,7 @@ PHP_FUNCTION(array_reduce)
zval args[2];
zval *operand;
zval *initial = NULL;
HashTable *htbl;
@@ -6515,7 +6515,7 @@ PHP_FUNCTION(array_filter)
zend_long use_type = 0;
zend_string *string_key;
zend_fcall_info fci = empty_fcall_info;
zend_ulong num_key;
ZEND_PARSE_PARAMETERS_START(1, 3)
@@ -6649,7 +6649,7 @@ PHP_FUNCTION(array_find)
@@ -6665,7 +6665,7 @@ PHP_FUNCTION(array_find_key)
@@ -6681,7 +6681,7 @@ PHP_FUNCTION(array_any)
@@ -6697,7 +6697,7 @@ PHP_FUNCTION(array_all)
@@ -6714,8 +6714,8 @@ PHP_FUNCTION(array_map)
zval *arrays = NULL;
int n_arrays = 0;
zval result;
- zend_fcall_info fci = empty_fcall_info;
+ zend_fcall_info fci;
int i;
uint32_t k, maxlen = 0; | [] | [] | {
"additions": 8,
"author": "nielsdos",
"deletions": 8,
"html_url": "https://github.com/php/php-src/pull/18273",
"issue_id": 18273,
"merged_at": "2025-04-15T21:08:13Z",
"omission_probability": 0.1,
"pr_number": 18273,
"repo": "php/php-src",
"title": "Avoid useless initializations of fci/fcc in array functions",
"total_changes": 16
} |
754 | diff --git a/Zend/tests/oss_fuzz_410939023.phpt b/Zend/tests/oss_fuzz_410939023.phpt
new file mode 100644
index 000000000000..9c024bf5b5b0
--- /dev/null
+++ b/Zend/tests/oss_fuzz_410939023.phpt
@@ -0,0 +1,11 @@
+--TEST--
+OSS-Fuzz #410939023: Use of magic const within const expr cast
+--FILE--
+<?php
+
+const C = (string)__METHOD__;
+var_dump(C);
+
+?>
+--EXPECT--
+string(0) ""
diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c
index 4f18999ffa78..5c15832f80a8 100644
--- a/Zend/zend_compile.c
+++ b/Zend/zend_compile.c
@@ -12127,6 +12127,9 @@ static void zend_eval_const_expr(zend_ast **ast_ptr) /* {{{ */
zend_eval_const_expr(&ast->child[0]);
zend_eval_const_expr(&ast->child[1]);
return;
+ case ZEND_AST_CAST:
+ zend_eval_const_expr(&ast->child[0]);
+ return;
default:
return;
}
| diff --git a/Zend/tests/oss_fuzz_410939023.phpt b/Zend/tests/oss_fuzz_410939023.phpt
new file mode 100644
index 000000000000..9c024bf5b5b0
--- /dev/null
+++ b/Zend/tests/oss_fuzz_410939023.phpt
@@ -0,0 +1,11 @@
+--TEST--
+OSS-Fuzz #410939023: Use of magic const within const expr cast
+--FILE--
+<?php
+const C = (string)__METHOD__;
+var_dump(C);
+?>
+--EXPECT--
diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c
index 4f18999ffa78..5c15832f80a8 100644
--- a/Zend/zend_compile.c
+++ b/Zend/zend_compile.c
@@ -12127,6 +12127,9 @@ static void zend_eval_const_expr(zend_ast **ast_ptr) /* {{{ */
zend_eval_const_expr(&ast->child[0]);
zend_eval_const_expr(&ast->child[1]);
+ case ZEND_AST_CAST:
+ zend_eval_const_expr(&ast->child[0]);
+ return;
default:
} | [
"+string(0) \"\""
] | [
16
] | {
"additions": 14,
"author": "iluuu1994",
"deletions": 0,
"html_url": "https://github.com/php/php-src/pull/18338",
"issue_id": 18338,
"merged_at": "2025-04-16T18:00:41Z",
"omission_probability": 0.1,
"pr_number": 18338,
"repo": "php/php-src",
"title": "Fix use of magic const within const expr cast",
"total_changes": 14
} |
755 | diff --git a/.gitignore b/.gitignore
index 91120a5fa6b2..55c441323cf1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -237,6 +237,7 @@ php
**/tests/**/*.exp
**/tests/**/*.log
**/tests/**/*.sh
+**/tests/**/*.stdin
# Generated by some test cases
**/tests/**/*.db
diff --git a/run-tests.php b/run-tests.php
index 0db6937c7a84..a90681c7ff7f 100755
--- a/run-tests.php
+++ b/run-tests.php
@@ -1934,6 +1934,7 @@ function run_test(string $php, $file, array $env): string
$diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'diff';
$log_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'log';
$exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'exp';
+ $stdin_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'stdin';
$output_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'out';
$memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'mem';
$sh_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'sh';
@@ -1972,6 +1973,7 @@ function run_test(string $php, $file, array $env): string
@unlink($diff_filename);
@unlink($log_filename);
@unlink($exp_filename);
+ @unlink($stdin_filename);
@unlink($output_filename);
@unlink($memcheck_filename);
@unlink($sh_filename);
@@ -2696,6 +2698,16 @@ function run_test(string $php, $file, array $env): string
$diff = generate_diff($wanted, $wanted_re, $output);
}
+ // write .stdin
+ if ($test->hasSection('STDIN') || $test->hasSection('PHPDBG')) {
+ $stdin = $test->hasSection('STDIN')
+ ? $test->getSection('STDIN')
+ : $test->getSection('PHPDBG') . "\n";
+ if (file_put_contents($stdin_filename, $stdin) === false) {
+ error("Cannot create test stdin - $stdin_filename");
+ }
+ }
+
if (is_array($IN_REDIRECT)) {
$orig_shortname = str_replace(TEST_PHP_SRCDIR . '/', '', $file);
$diff = "# original source file: $orig_shortname\n" . $diff;
| diff --git a/.gitignore b/.gitignore
index 91120a5fa6b2..55c441323cf1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -237,6 +237,7 @@ php
**/tests/**/*.exp
**/tests/**/*.log
**/tests/**/*.sh
+**/tests/**/*.stdin
# Generated by some test cases
**/tests/**/*.db
diff --git a/run-tests.php b/run-tests.php
index 0db6937c7a84..a90681c7ff7f 100755
--- a/run-tests.php
+++ b/run-tests.php
@@ -1934,6 +1934,7 @@ function run_test(string $php, $file, array $env): string
$diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'diff';
$log_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'log';
$exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'exp';
+ $stdin_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'stdin';
$output_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'out';
$memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'mem';
$sh_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'sh';
@@ -1972,6 +1973,7 @@ function run_test(string $php, $file, array $env): string
@unlink($diff_filename);
@unlink($log_filename);
@unlink($exp_filename);
+ @unlink($stdin_filename);
@unlink($output_filename);
@unlink($memcheck_filename);
@unlink($sh_filename);
@@ -2696,6 +2698,16 @@ function run_test(string $php, $file, array $env): string
$diff = generate_diff($wanted, $wanted_re, $output);
}
+ // write .stdin
+ if ($test->hasSection('STDIN') || $test->hasSection('PHPDBG')) {
+ $stdin = $test->hasSection('STDIN')
+ ? $test->getSection('STDIN')
+ if (file_put_contents($stdin_filename, $stdin) === false) {
+ error("Cannot create test stdin - $stdin_filename");
+ }
+ }
+
if (is_array($IN_REDIRECT)) {
$orig_shortname = str_replace(TEST_PHP_SRCDIR . '/', '', $file);
$diff = "# original source file: $orig_shortname\n" . $diff; | [
"+ : $test->getSection('PHPDBG') . \"\\n\";"
] | [
40
] | {
"additions": 13,
"author": "arnaud-lb",
"deletions": 0,
"html_url": "https://github.com/php/php-src/pull/18305",
"issue_id": 18305,
"merged_at": "2025-04-15T12:02:08Z",
"omission_probability": 0.1,
"pr_number": 18305,
"repo": "php/php-src",
"title": "run-tests.php: Save STDIN section into a file",
"total_changes": 13
} |
756 | diff --git a/Zend/tests/type_casts/gh18301_cast_to_void_for.phpt b/Zend/tests/type_casts/gh18301_cast_to_void_for.phpt
new file mode 100644
index 0000000000000..2ff7cfb0cb17b
--- /dev/null
+++ b/Zend/tests/type_casts/gh18301_cast_to_void_for.phpt
@@ -0,0 +1,46 @@
+--TEST--
+GH-18301: casting to void is allowed in for’s expression lists
+--FILE--
+<?php
+
+$count = 0;
+
+#[NoDiscard]
+function incCount() {
+ global $count;
+ $count++;
+ return $count;
+}
+
+for ( $count = 0, (void)incCount(), incCount(); (void)incCount(), incCount() < 30; incCount(), $count++, incCount(), (void)incCount()) {
+ echo $count . "\n";
+}
+
+?>
+--EXPECTF--
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+4
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+10
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+16
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+22
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+28
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
+
+Warning: The return value of function incCount() should either be used or intentionally ignored by casting it as (void) in %s on line %d
diff --git a/Zend/tests/type_casts/gh18301_cast_to_void_statement_for_condition.phpt b/Zend/tests/type_casts/gh18301_cast_to_void_statement_for_condition.phpt
new file mode 100644
index 0000000000000..6c90b2f7987c6
--- /dev/null
+++ b/Zend/tests/type_casts/gh18301_cast_to_void_statement_for_condition.phpt
@@ -0,0 +1,9 @@
+--TEST--
+GH-18301: casting to void is not allowed at the end of a for condition
+--FILE--
+<?php
+
+for (;(void)true;);
+?>
+--EXPECTF--
+Parse error: syntax error, unexpected token ";", expecting "," in %s on line %d
diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c
index 2ad3f6b323d8f..5414d686d9826 100644
--- a/Zend/zend_compile.c
+++ b/Zend/zend_compile.c
@@ -5717,6 +5717,26 @@ static void zend_compile_return(zend_ast *ast) /* {{{ */
}
/* }}} */
+static void zend_compile_void_cast(znode *result, zend_ast *ast)
+{
+ zend_ast *expr_ast = ast->child[0];
+ znode expr_node;
+ zend_op *opline;
+
+ zend_compile_expr(&expr_node, expr_ast);
+
+ switch (expr_node.op_type) {
+ case IS_TMP_VAR:
+ case IS_VAR:
+ opline = zend_emit_op(NULL, ZEND_FREE, &expr_node, NULL);
+ opline->extended_value = ZEND_FREE_VOID_CAST;
+ break;
+ case IS_CONST:
+ zend_do_free(&expr_node);
+ break;
+ }
+}
+
static void zend_compile_echo(zend_ast *ast) /* {{{ */
{
zend_op *opline;
@@ -5967,7 +5987,7 @@ static void zend_compile_do_while(zend_ast *ast) /* {{{ */
}
/* }}} */
-static void zend_compile_expr_list(znode *result, zend_ast *ast) /* {{{ */
+static void zend_compile_for_expr_list(znode *result, zend_ast *ast) /* {{{ */
{
zend_ast_list *list;
uint32_t i;
@@ -5984,7 +6004,13 @@ static void zend_compile_expr_list(znode *result, zend_ast *ast) /* {{{ */
zend_ast *expr_ast = list->child[i];
zend_do_free(result);
- zend_compile_expr(result, expr_ast);
+ if (expr_ast->kind == ZEND_AST_CAST_VOID) {
+ zend_compile_void_cast(NULL, expr_ast);
+ result->op_type = IS_CONST;
+ ZVAL_NULL(&result->u.constant);
+ } else {
+ zend_compile_expr(result, expr_ast);
+ }
}
}
/* }}} */
@@ -5999,7 +6025,7 @@ static void zend_compile_for(zend_ast *ast) /* {{{ */
znode result;
uint32_t opnum_start, opnum_jmp, opnum_loop;
- zend_compile_expr_list(&result, init_ast);
+ zend_compile_for_expr_list(&result, init_ast);
zend_do_free(&result);
opnum_jmp = zend_emit_jump(0);
@@ -6010,11 +6036,11 @@ static void zend_compile_for(zend_ast *ast) /* {{{ */
zend_compile_stmt(stmt_ast);
opnum_loop = get_next_op_number();
- zend_compile_expr_list(&result, loop_ast);
+ zend_compile_for_expr_list(&result, loop_ast);
zend_do_free(&result);
zend_update_jump_target_to_next(opnum_jmp);
- zend_compile_expr_list(&result, cond_ast);
+ zend_compile_for_expr_list(&result, cond_ast);
zend_do_extended_stmt();
zend_emit_cond_jump(ZEND_JMPNZ, &result, opnum_start);
@@ -10594,26 +10620,6 @@ static void zend_compile_include_or_eval(znode *result, zend_ast *ast) /* {{{ */
}
/* }}} */
-static void zend_compile_void_cast(znode *result, zend_ast *ast)
-{
- zend_ast *expr_ast = ast->child[0];
- znode expr_node;
- zend_op *opline;
-
- zend_compile_expr(&expr_node, expr_ast);
-
- switch (expr_node.op_type) {
- case IS_TMP_VAR:
- case IS_VAR:
- opline = zend_emit_op(NULL, ZEND_FREE, &expr_node, NULL);
- opline->extended_value = ZEND_FREE_VOID_CAST;
- break;
- case IS_CONST:
- zend_do_free(&expr_node);
- break;
- }
-}
-
static void zend_compile_isset_or_empty(znode *result, zend_ast *ast) /* {{{ */
{
zend_ast *var_ast = ast->child[0];
diff --git a/Zend/zend_language_parser.y b/Zend/zend_language_parser.y
index 9483a83b4e955..190292fada760 100644
--- a/Zend/zend_language_parser.y
+++ b/Zend/zend_language_parser.y
@@ -268,7 +268,7 @@ static YYSIZE_T zend_yytnamerr(char*, const char*);
%type <ast> callable_expr callable_variable static_member new_variable
%type <ast> encaps_var encaps_var_offset isset_variables
%type <ast> top_statement_list use_declarations const_list inner_statement_list if_stmt
-%type <ast> alt_if_stmt for_exprs switch_case_list global_var_list static_var_list
+%type <ast> alt_if_stmt for_cond_exprs for_exprs switch_case_list global_var_list static_var_list
%type <ast> echo_expr_list unset_variables catch_name_list catch_list optional_variable parameter_list class_statement_list
%type <ast> implements_list case_list if_stmt_without_else
%type <ast> non_empty_parameter_list argument_list non_empty_argument_list property_list
@@ -508,7 +508,7 @@ statement:
{ $$ = zend_ast_create(ZEND_AST_WHILE, $3, $5); }
| T_DO statement T_WHILE '(' expr ')' ';'
{ $$ = zend_ast_create(ZEND_AST_DO_WHILE, $2, $5); }
- | T_FOR '(' for_exprs ';' for_exprs ';' for_exprs ')' for_statement
+ | T_FOR '(' for_exprs ';' for_cond_exprs ';' for_exprs ')' for_statement
{ $$ = zend_ast_create(ZEND_AST_FOR, $3, $5, $7, $9); }
| T_SWITCH '(' expr ')' switch_case_list
{ $$ = zend_ast_create(ZEND_AST_SWITCH, $3, $5); }
@@ -1169,6 +1169,12 @@ echo_expr:
expr { $$ = zend_ast_create(ZEND_AST_ECHO, $1); }
;
+for_cond_exprs:
+ %empty { $$ = NULL; }
+ | non_empty_for_exprs ',' expr { $$ = zend_ast_list_add($1, $3); }
+ | expr { $$ = zend_ast_create_list(1, ZEND_AST_EXPR_LIST, $1); }
+;
+
for_exprs:
%empty { $$ = NULL; }
| non_empty_for_exprs { $$ = $1; }
@@ -1176,6 +1182,8 @@ for_exprs:
non_empty_for_exprs:
non_empty_for_exprs ',' expr { $$ = zend_ast_list_add($1, $3); }
+ | non_empty_for_exprs ',' T_VOID_CAST expr { $$ = zend_ast_list_add($1, zend_ast_create(ZEND_AST_CAST_VOID, $4)); }
+ | T_VOID_CAST expr { $$ = zend_ast_create_list(1, ZEND_AST_EXPR_LIST, zend_ast_create(ZEND_AST_CAST_VOID, $2)); }
| expr { $$ = zend_ast_create_list(1, ZEND_AST_EXPR_LIST, $1); }
;
| diff --git a/Zend/tests/type_casts/gh18301_cast_to_void_for.phpt b/Zend/tests/type_casts/gh18301_cast_to_void_for.phpt
index 0000000000000..2ff7cfb0cb17b
+++ b/Zend/tests/type_casts/gh18301_cast_to_void_for.phpt
@@ -0,0 +1,46 @@
+GH-18301: casting to void is allowed in for’s expression lists
+$count = 0;
+#[NoDiscard]
+function incCount() {
+ global $count;
+ return $count;
+for ( $count = 0, (void)incCount(), incCount(); (void)incCount(), incCount() < 30; incCount(), $count++, incCount(), (void)incCount()) {
+ echo $count . "\n";
+4
+10
+16
+22
+28
diff --git a/Zend/tests/type_casts/gh18301_cast_to_void_statement_for_condition.phpt b/Zend/tests/type_casts/gh18301_cast_to_void_statement_for_condition.phpt
index 0000000000000..6c90b2f7987c6
+++ b/Zend/tests/type_casts/gh18301_cast_to_void_statement_for_condition.phpt
@@ -0,0 +1,9 @@
+GH-18301: casting to void is not allowed at the end of a for condition
+for (;(void)true;);
+Parse error: syntax error, unexpected token ";", expecting "," in %s on line %d
diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c
index 2ad3f6b323d8f..5414d686d9826 100644
--- a/Zend/zend_compile.c
+++ b/Zend/zend_compile.c
@@ -5717,6 +5717,26 @@ static void zend_compile_return(zend_ast *ast) /* {{{ */
+static void zend_compile_void_cast(znode *result, zend_ast *ast)
+{
+ zend_ast *expr_ast = ast->child[0];
+ znode expr_node;
+ zend_op *opline;
+ zend_compile_expr(&expr_node, expr_ast);
+ switch (expr_node.op_type) {
+ case IS_TMP_VAR:
+ case IS_VAR:
+ opline = zend_emit_op(NULL, ZEND_FREE, &expr_node, NULL);
+ case IS_CONST:
+ zend_do_free(&expr_node);
+ }
static void zend_compile_echo(zend_ast *ast) /* {{{ */
zend_op *opline;
@@ -5967,7 +5987,7 @@ static void zend_compile_do_while(zend_ast *ast) /* {{{ */
-static void zend_compile_expr_list(znode *result, zend_ast *ast) /* {{{ */
+static void zend_compile_for_expr_list(znode *result, zend_ast *ast) /* {{{ */
zend_ast_list *list;
uint32_t i;
@@ -5984,7 +6004,13 @@ static void zend_compile_expr_list(znode *result, zend_ast *ast) /* {{{ */
zend_ast *expr_ast = list->child[i];
zend_do_free(result);
- zend_compile_expr(result, expr_ast);
+ if (expr_ast->kind == ZEND_AST_CAST_VOID) {
+ zend_compile_void_cast(NULL, expr_ast);
+ result->op_type = IS_CONST;
+ ZVAL_NULL(&result->u.constant);
+ } else {
+ zend_compile_expr(result, expr_ast);
+ }
}
@@ -5999,7 +6025,7 @@ static void zend_compile_for(zend_ast *ast) /* {{{ */
znode result;
uint32_t opnum_start, opnum_jmp, opnum_loop;
- zend_compile_expr_list(&result, init_ast);
+ zend_compile_for_expr_list(&result, init_ast);
opnum_jmp = zend_emit_jump(0);
@@ -6010,11 +6036,11 @@ static void zend_compile_for(zend_ast *ast) /* {{{ */
zend_compile_stmt(stmt_ast);
opnum_loop = get_next_op_number();
- zend_compile_expr_list(&result, loop_ast);
+ zend_compile_for_expr_list(&result, loop_ast);
zend_update_jump_target_to_next(opnum_jmp);
- zend_compile_expr_list(&result, cond_ast);
zend_do_extended_stmt();
zend_emit_cond_jump(ZEND_JMPNZ, &result, opnum_start);
@@ -10594,26 +10620,6 @@ static void zend_compile_include_or_eval(znode *result, zend_ast *ast) /* {{{ */
-static void zend_compile_void_cast(znode *result, zend_ast *ast)
- zend_ast *expr_ast = ast->child[0];
- znode expr_node;
- zend_op *opline;
- zend_compile_expr(&expr_node, expr_ast);
- switch (expr_node.op_type) {
- case IS_TMP_VAR:
- case IS_VAR:
- opline = zend_emit_op(NULL, ZEND_FREE, &expr_node, NULL);
- opline->extended_value = ZEND_FREE_VOID_CAST;
- case IS_CONST:
- zend_do_free(&expr_node);
- }
-}
static void zend_compile_isset_or_empty(znode *result, zend_ast *ast) /* {{{ */
zend_ast *var_ast = ast->child[0];
diff --git a/Zend/zend_language_parser.y b/Zend/zend_language_parser.y
index 9483a83b4e955..190292fada760 100644
--- a/Zend/zend_language_parser.y
+++ b/Zend/zend_language_parser.y
@@ -268,7 +268,7 @@ static YYSIZE_T zend_yytnamerr(char*, const char*);
%type <ast> callable_expr callable_variable static_member new_variable
%type <ast> encaps_var encaps_var_offset isset_variables
%type <ast> top_statement_list use_declarations const_list inner_statement_list if_stmt
-%type <ast> alt_if_stmt for_exprs switch_case_list global_var_list static_var_list
+%type <ast> alt_if_stmt for_cond_exprs for_exprs switch_case_list global_var_list static_var_list
%type <ast> echo_expr_list unset_variables catch_name_list catch_list optional_variable parameter_list class_statement_list
%type <ast> implements_list case_list if_stmt_without_else
%type <ast> non_empty_parameter_list argument_list non_empty_argument_list property_list
@@ -508,7 +508,7 @@ statement:
{ $$ = zend_ast_create(ZEND_AST_WHILE, $3, $5); }
| T_DO statement T_WHILE '(' expr ')' ';'
{ $$ = zend_ast_create(ZEND_AST_DO_WHILE, $2, $5); }
- | T_FOR '(' for_exprs ';' for_exprs ';' for_exprs ')' for_statement
+ | T_FOR '(' for_exprs ';' for_cond_exprs ';' for_exprs ')' for_statement
{ $$ = zend_ast_create(ZEND_AST_FOR, $3, $5, $7, $9); }
| T_SWITCH '(' expr ')' switch_case_list
{ $$ = zend_ast_create(ZEND_AST_SWITCH, $3, $5); }
@@ -1169,6 +1169,12 @@ echo_expr:
expr { $$ = zend_ast_create(ZEND_AST_ECHO, $1); }
+for_cond_exprs:
+ %empty { $$ = NULL; }
+ | non_empty_for_exprs ',' expr { $$ = zend_ast_list_add($1, $3); }
+ | expr { $$ = zend_ast_create_list(1, ZEND_AST_EXPR_LIST, $1); }
+;
for_exprs:
%empty { $$ = NULL; }
| non_empty_for_exprs { $$ = $1; }
@@ -1176,6 +1182,8 @@ for_exprs:
non_empty_for_exprs:
non_empty_for_exprs ',' expr { $$ = zend_ast_list_add($1, $3); }
+ | non_empty_for_exprs ',' T_VOID_CAST expr { $$ = zend_ast_list_add($1, zend_ast_create(ZEND_AST_CAST_VOID, $4)); }
+ | T_VOID_CAST expr { $$ = zend_ast_create_list(1, ZEND_AST_EXPR_LIST, zend_ast_create(ZEND_AST_CAST_VOID, $2)); }
| expr { $$ = zend_ast_create_list(1, ZEND_AST_EXPR_LIST, $1); } | [
"+\t$count++;",
"+\t\t\topline->extended_value = ZEND_FREE_VOID_CAST;",
"+\tzend_compile_for_expr_list(&result, cond_ast);",
"-{"
] | [
16,
87,
141,
150
] | {
"additions": 96,
"author": "TimWolla",
"deletions": 27,
"html_url": "https://github.com/php/php-src/pull/18303",
"issue_id": 18303,
"merged_at": "2025-04-14T13:36:52Z",
"omission_probability": 0.1,
"pr_number": 18303,
"repo": "php/php-src",
"title": "zend_compile: Allow `(void)` in for’s initializer and loop expression",
"total_changes": 123
} |
757 | diff --git a/ext/iconv/iconv.c b/ext/iconv/iconv.c
index b61d253c5d4be..157ee41a11a05 100644
--- a/ext/iconv/iconv.c
+++ b/ext/iconv/iconv.c
@@ -63,15 +63,15 @@
#define PHP_ICONV_IMPL_VALUE "unknown"
#endif
-static char *get_iconv_version(void) {
- char *version = "unknown";
+static const char *get_iconv_version(void) {
+ const char *version = "unknown";
#ifdef HAVE_LIBICONV
static char buf[16];
snprintf(buf, sizeof(buf), "%d.%d", _libiconv_version >> 8, _libiconv_version & 0xff);
version = buf;
#elif defined(HAVE_GLIBC_ICONV)
- version = (char *) gnu_get_libc_version();
+ version = gnu_get_libc_version();
#endif
return version;
@@ -243,7 +243,7 @@ PHP_MSHUTDOWN_FUNCTION(miconv)
/* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(miconv)
{
- zval *iconv_impl, *iconv_ver;
+ const zval *iconv_impl, *iconv_ver;
iconv_impl = zend_get_constant_str("ICONV_IMPL", sizeof("ICONV_IMPL")-1);
iconv_ver = zend_get_constant_str("ICONV_VERSION", sizeof("ICONV_VERSION")-1);
@@ -298,17 +298,18 @@ static php_output_handler *php_iconv_output_handler_init(const char *handler_nam
static zend_result php_iconv_output_handler(void **nothing, php_output_context *output_context)
{
- char *s, *content_type, *mimetype = NULL;
- int output_status, mimetype_len = 0;
+ char *content_type, *mimetype = NULL;
if (output_context->op & PHP_OUTPUT_HANDLER_START) {
- output_status = php_output_get_status();
+ int output_status = php_output_get_status();
if (output_status & PHP_OUTPUT_SENT) {
return FAILURE;
}
+ int mimetype_len = 0;
if (SG(sapi_headers).mimetype && !strncasecmp(SG(sapi_headers).mimetype, "text/", 5)) {
- if ((s = strchr(SG(sapi_headers).mimetype,';')) == NULL){
+ const char *s = strchr(SG(sapi_headers).mimetype,';');
+ if (s == NULL){
mimetype = SG(sapi_headers).mimetype;
} else {
mimetype = SG(sapi_headers).mimetype;
@@ -320,7 +321,7 @@ static zend_result php_iconv_output_handler(void **nothing, php_output_context *
if (mimetype != NULL && (!(output_context->op & PHP_OUTPUT_HANDLER_CLEAN) || ((output_context->op & PHP_OUTPUT_HANDLER_START) && !(output_context->op & PHP_OUTPUT_HANDLER_FINAL)))) {
size_t len;
- char *p = strstr(get_output_encoding(), "//");
+ const char *p = strstr(get_output_encoding(), "//");
if (p) {
len = spprintf(&content_type, 0, "Content-Type:%.*s; charset=%.*s", mimetype_len ? mimetype_len : (int) strlen(mimetype), mimetype, (int) (p - get_output_encoding()), get_output_encoding());
@@ -417,16 +418,16 @@ static php_iconv_err_t _php_iconv_appendc(smart_str *d, const char c, iconv_t cd
/* {{{ */
#ifdef ICONV_BROKEN_IGNORE
-static int _php_check_ignore(const char *charset)
+static bool _php_check_ignore(const char *charset)
{
size_t clen = strlen(charset);
if (clen >= 9 && strcmp("//IGNORE", charset+clen-8) == 0) {
- return 1;
+ return true;
}
if (clen >= 19 && strcmp("//IGNORE//TRANSLIT", charset+clen-18) == 0) {
- return 1;
+ return true;
}
- return 0;
+ return false;
}
#else
#define _php_check_ignore(x) (0)
@@ -442,7 +443,7 @@ PHP_ICONV_API php_iconv_err_t php_iconv_string(const char *in_p, size_t in_len,
size_t bsz, result = 0;
php_iconv_err_t retval = PHP_ICONV_ERR_SUCCESS;
zend_string *out_buf;
- int ignore_ilseq = _php_check_ignore(out_charset);
+ bool ignore_ilseq = _php_check_ignore(out_charset);
*out = NULL;
@@ -559,7 +560,7 @@ static php_iconv_err_t _php_iconv_strlen(size_t *pretval, const char *str, size_
size_t out_left;
size_t cnt;
- int more;
+ bool more;
*pretval = (size_t)-1;
@@ -636,7 +637,7 @@ static php_iconv_err_t _php_iconv_substr(smart_str *pretval,
size_t cnt;
size_t total_len;
- int more;
+ bool more;
err = _php_iconv_strlen(&total_len, str, nbytes, enc);
if (err != PHP_ICONV_ERR_SUCCESS) {
@@ -774,8 +775,7 @@ static php_iconv_err_t _php_iconv_strpos(size_t *pretval,
size_t ndl_buf_left;
size_t match_ofs;
- int more;
- size_t iconv_ret;
+ bool more;
*pretval = (size_t)-1;
@@ -812,7 +812,7 @@ static php_iconv_err_t _php_iconv_strpos(size_t *pretval,
more = in_left > 0;
- iconv_ret = iconv(cd, more ? (ICONV_CONST char **)&in_p : NULL, more ? &in_left : NULL, (char **) &out_p, &out_left);
+ size_t iconv_ret = iconv(cd, more ? (ICONV_CONST char **)&in_p : NULL, more ? &in_left : NULL, (char **) &out_p, &out_left);
if (out_left == sizeof(buf)) {
break;
}
@@ -2255,11 +2255,7 @@ PHP_FUNCTION(iconv_set_encoding)
retval = zend_alter_ini_entry(name, charset, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_string_release_ex(name, 0);
- if (retval == SUCCESS) {
- RETURN_TRUE;
- } else {
- RETURN_FALSE;
- }
+ RETURN_BOOL(retval == SUCCESS);
}
/* }}} */
@@ -2577,7 +2573,7 @@ static php_stream_filter *php_iconv_stream_filter_factory_create(const char *nam
{
php_stream_filter *retval = NULL;
php_iconv_stream_filter *inst;
- char *from_charset = NULL, *to_charset = NULL;
+ const char *from_charset = NULL, *to_charset = NULL;
size_t from_charset_len, to_charset_len;
if ((from_charset = strchr(name, '.')) == NULL) {
diff --git a/ext/iconv/php_iconv.h b/ext/iconv/php_iconv.h
index 7bc1cce0df9f5..fcabdfaf6449e 100644
--- a/ext/iconv/php_iconv.h
+++ b/ext/iconv/php_iconv.h
@@ -67,7 +67,7 @@ ZEND_TSRMLS_CACHE_EXTERN()
/* {{{ typedef enum php_iconv_err_t */
typedef enum _php_iconv_err_t {
- PHP_ICONV_ERR_SUCCESS = SUCCESS,
+ PHP_ICONV_ERR_SUCCESS = 0,
PHP_ICONV_ERR_CONVERTER = 1,
PHP_ICONV_ERR_WRONG_CHARSET = 2,
PHP_ICONV_ERR_TOO_BIG = 3,
| diff --git a/ext/iconv/iconv.c b/ext/iconv/iconv.c
index b61d253c5d4be..157ee41a11a05 100644
--- a/ext/iconv/iconv.c
+++ b/ext/iconv/iconv.c
@@ -63,15 +63,15 @@
#define PHP_ICONV_IMPL_VALUE "unknown"
-static char *get_iconv_version(void) {
+static const char *get_iconv_version(void) {
+ const char *version = "unknown";
#ifdef HAVE_LIBICONV
static char buf[16];
snprintf(buf, sizeof(buf), "%d.%d", _libiconv_version >> 8, _libiconv_version & 0xff);
version = buf;
#elif defined(HAVE_GLIBC_ICONV)
- version = (char *) gnu_get_libc_version();
+ version = gnu_get_libc_version();
return version;
@@ -243,7 +243,7 @@ PHP_MSHUTDOWN_FUNCTION(miconv)
/* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(miconv)
- zval *iconv_impl, *iconv_ver;
+ const zval *iconv_impl, *iconv_ver;
iconv_impl = zend_get_constant_str("ICONV_IMPL", sizeof("ICONV_IMPL")-1);
iconv_ver = zend_get_constant_str("ICONV_VERSION", sizeof("ICONV_VERSION")-1);
@@ -298,17 +298,18 @@ static php_output_handler *php_iconv_output_handler_init(const char *handler_nam
static zend_result php_iconv_output_handler(void **nothing, php_output_context *output_context)
- char *s, *content_type, *mimetype = NULL;
+ char *content_type, *mimetype = NULL;
if (output_context->op & PHP_OUTPUT_HANDLER_START) {
- output_status = php_output_get_status();
+ int output_status = php_output_get_status();
if (output_status & PHP_OUTPUT_SENT) {
return FAILURE;
+ int mimetype_len = 0;
if (SG(sapi_headers).mimetype && !strncasecmp(SG(sapi_headers).mimetype, "text/", 5)) {
- if ((s = strchr(SG(sapi_headers).mimetype,';')) == NULL){
+ const char *s = strchr(SG(sapi_headers).mimetype,';');
+ if (s == NULL){
} else {
@@ -320,7 +321,7 @@ static zend_result php_iconv_output_handler(void **nothing, php_output_context *
if (mimetype != NULL && (!(output_context->op & PHP_OUTPUT_HANDLER_CLEAN) || ((output_context->op & PHP_OUTPUT_HANDLER_START) && !(output_context->op & PHP_OUTPUT_HANDLER_FINAL)))) {
size_t len;
- char *p = strstr(get_output_encoding(), "//");
+ const char *p = strstr(get_output_encoding(), "//");
if (p) {
len = spprintf(&content_type, 0, "Content-Type:%.*s; charset=%.*s", mimetype_len ? mimetype_len : (int) strlen(mimetype), mimetype, (int) (p - get_output_encoding()), get_output_encoding());
@@ -417,16 +418,16 @@ static php_iconv_err_t _php_iconv_appendc(smart_str *d, const char c, iconv_t cd
/* {{{ */
#ifdef ICONV_BROKEN_IGNORE
-static int _php_check_ignore(const char *charset)
+static bool _php_check_ignore(const char *charset)
size_t clen = strlen(charset);
if (clen >= 9 && strcmp("//IGNORE", charset+clen-8) == 0) {
if (clen >= 19 && strcmp("//IGNORE//TRANSLIT", charset+clen-18) == 0) {
- return 0;
+ return false;
#else
#define _php_check_ignore(x) (0)
@@ -442,7 +443,7 @@ PHP_ICONV_API php_iconv_err_t php_iconv_string(const char *in_p, size_t in_len,
size_t bsz, result = 0;
php_iconv_err_t retval = PHP_ICONV_ERR_SUCCESS;
zend_string *out_buf;
- int ignore_ilseq = _php_check_ignore(out_charset);
+ bool ignore_ilseq = _php_check_ignore(out_charset);
*out = NULL;
@@ -559,7 +560,7 @@ static php_iconv_err_t _php_iconv_strlen(size_t *pretval, const char *str, size_
size_t out_left;
@@ -636,7 +637,7 @@ static php_iconv_err_t _php_iconv_substr(smart_str *pretval,
size_t total_len;
err = _php_iconv_strlen(&total_len, str, nbytes, enc);
if (err != PHP_ICONV_ERR_SUCCESS) {
@@ -774,8 +775,7 @@ static php_iconv_err_t _php_iconv_strpos(size_t *pretval,
size_t ndl_buf_left;
size_t match_ofs;
- size_t iconv_ret;
@@ -812,7 +812,7 @@ static php_iconv_err_t _php_iconv_strpos(size_t *pretval,
more = in_left > 0;
- iconv_ret = iconv(cd, more ? (ICONV_CONST char **)&in_p : NULL, more ? &in_left : NULL, (char **) &out_p, &out_left);
+ size_t iconv_ret = iconv(cd, more ? (ICONV_CONST char **)&in_p : NULL, more ? &in_left : NULL, (char **) &out_p, &out_left);
if (out_left == sizeof(buf)) {
break;
@@ -2255,11 +2255,7 @@ PHP_FUNCTION(iconv_set_encoding)
retval = zend_alter_ini_entry(name, charset, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_string_release_ex(name, 0);
- if (retval == SUCCESS) {
- RETURN_TRUE;
- } else {
- RETURN_FALSE;
- }
+ RETURN_BOOL(retval == SUCCESS);
/* }}} */
@@ -2577,7 +2573,7 @@ static php_stream_filter *php_iconv_stream_filter_factory_create(const char *nam
php_stream_filter *retval = NULL;
php_iconv_stream_filter *inst;
- char *from_charset = NULL, *to_charset = NULL;
+ const char *from_charset = NULL, *to_charset = NULL;
size_t from_charset_len, to_charset_len;
if ((from_charset = strchr(name, '.')) == NULL) {
diff --git a/ext/iconv/php_iconv.h b/ext/iconv/php_iconv.h
index 7bc1cce0df9f5..fcabdfaf6449e 100644
--- a/ext/iconv/php_iconv.h
+++ b/ext/iconv/php_iconv.h
@@ -67,7 +67,7 @@ ZEND_TSRMLS_CACHE_EXTERN()
/* {{{ typedef enum php_iconv_err_t */
typedef enum _php_iconv_err_t {
- PHP_ICONV_ERR_SUCCESS = SUCCESS,
+ PHP_ICONV_ERR_SUCCESS = 0,
PHP_ICONV_ERR_CONVERTER = 1,
PHP_ICONV_ERR_WRONG_CHARSET = 2,
PHP_ICONV_ERR_TOO_BIG = 3, | [
"-\tchar *version = \"unknown\";",
"-\tint output_status, mimetype_len = 0;"
] | [
9,
37
] | {
"additions": 22,
"author": "Girgias",
"deletions": 26,
"html_url": "https://github.com/php/php-src/pull/18313",
"issue_id": 18313,
"merged_at": "2025-04-14T09:15:55Z",
"omission_probability": 0.1,
"pr_number": 18313,
"repo": "php/php-src",
"title": "ext/iconv: Various minor refactorings",
"total_changes": 48
} |
758 | diff --git a/ext/spl/spl_directory.c b/ext/spl/spl_directory.c
index 461bdc1e901ec..751000fe63004 100644
--- a/ext/spl/spl_directory.c
+++ b/ext/spl/spl_directory.c
@@ -1599,12 +1599,12 @@ PHP_METHOD(GlobIterator, count)
RETURN_THROWS();
}
- /* The spl_filesystem_object_get_method_check() function is called prior to calling this function.
- * Therefore, the directory entry cannot be NULL. However, if it is not NULL, then it must be a glob iterator
- * by construction. */
- ZEND_ASSERT(spl_intern_is_glob(intern));
-
- RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
+ if (EXPECTED(spl_intern_is_glob(intern))) {
+ RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
+ } else {
+ /* This can happen by avoiding constructors in specially-crafted code. */
+ zend_throw_error(NULL, "GlobIterator is not initialized");
+ }
}
/* }}} */
#endif /* HAVE_GLOB */
diff --git a/ext/spl/tests/GlobIterator_constructor_count.phpt b/ext/spl/tests/GlobIterator_constructor_count.phpt
new file mode 100644
index 0000000000000..5f96be6219d62
--- /dev/null
+++ b/ext/spl/tests/GlobIterator_constructor_count.phpt
@@ -0,0 +1,14 @@
+--TEST--
+GlobIterator without constructor breaks count()
+--FILE--
+<?php
+$rc = new ReflectionClass(GlobIterator::class);
+$in = $rc->newInstanceWithoutConstructor();
+try {
+ count($in);
+} catch (Error $e) {
+ echo $e->getMessage(), "\n";
+}
+?>
+--EXPECT--
+GlobIterator is not initialized
| diff --git a/ext/spl/spl_directory.c b/ext/spl/spl_directory.c
index 461bdc1e901ec..751000fe63004 100644
--- a/ext/spl/spl_directory.c
+++ b/ext/spl/spl_directory.c
@@ -1599,12 +1599,12 @@ PHP_METHOD(GlobIterator, count)
RETURN_THROWS();
}
- /* The spl_filesystem_object_get_method_check() function is called prior to calling this function.
- * Therefore, the directory entry cannot be NULL. However, if it is not NULL, then it must be a glob iterator
- * by construction. */
- ZEND_ASSERT(spl_intern_is_glob(intern));
-
- RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
+ if (EXPECTED(spl_intern_is_glob(intern))) {
+ RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
+ } else {
+ /* This can happen by avoiding constructors in specially-crafted code. */
+ zend_throw_error(NULL, "GlobIterator is not initialized");
+ }
}
/* }}} */
#endif /* HAVE_GLOB */
diff --git a/ext/spl/tests/GlobIterator_constructor_count.phpt b/ext/spl/tests/GlobIterator_constructor_count.phpt
new file mode 100644
index 0000000000000..5f96be6219d62
--- /dev/null
+++ b/ext/spl/tests/GlobIterator_constructor_count.phpt
@@ -0,0 +1,14 @@
+--TEST--
+GlobIterator without constructor breaks count()
+--FILE--
+<?php
+$rc = new ReflectionClass(GlobIterator::class);
+$in = $rc->newInstanceWithoutConstructor();
+try {
+ count($in);
+} catch (Error $e) {
+ echo $e->getMessage(), "\n";
+}
+?>
+--EXPECT--
+GlobIterator is not initialized | [] | [] | {
"additions": 20,
"author": "nielsdos",
"deletions": 6,
"html_url": "https://github.com/php/php-src/pull/18314",
"issue_id": 18314,
"merged_at": "2025-04-12T07:59:57Z",
"omission_probability": 0.1,
"pr_number": 18314,
"repo": "php/php-src",
"title": "Fix GlobIterator without constructor breaks count()",
"total_changes": 26
} |
759 | diff --git a/ext/bcmath/bcmath.c b/ext/bcmath/bcmath.c
index 962f839ba83f4..1e0e6d14d81eb 100644
--- a/ext/bcmath/bcmath.c
+++ b/ext/bcmath/bcmath.c
@@ -1164,7 +1164,7 @@ static zend_always_inline bcmath_number_obj_t *bcmath_number_new_obj(bc_num ret,
return intern;
}
-static zend_result bcmath_number_parse_num(zval *zv, zend_object **obj, zend_string **str, zend_long *lval)
+static zend_result bcmath_number_parse_num(const zval *zv, zend_object **obj, zend_string **str, zend_long *lval)
{
if (Z_TYPE_P(zv) == IS_OBJECT && instanceof_function(Z_OBJCE_P(zv), bcmath_number_ce)) {
*obj = Z_OBJ_P(zv);
@@ -1372,7 +1372,7 @@ static int bcmath_number_compare(zval *op1, zval *op2)
}
static zend_always_inline zend_result bc_num_from_obj_or_str_or_long_with_err(
- bc_num *num, size_t *scale, zend_object *obj, zend_string *str, zend_long lval, uint32_t arg_num)
+ bc_num *num, size_t *scale, const zend_object *obj, const zend_string *str, zend_long lval, uint32_t arg_num)
{
size_t full_scale = 0;
if (UNEXPECTED(bc_num_from_obj_or_str_or_long(num, &full_scale, obj, str, lval) == FAILURE)) {
diff --git a/ext/bcmath/libbcmath/src/compare.c b/ext/bcmath/libbcmath/src/compare.c
index 2c24dab777059..06ef246782089 100644
--- a/ext/bcmath/libbcmath/src/compare.c
+++ b/ext/bcmath/libbcmath/src/compare.c
@@ -41,8 +41,6 @@
bcmath_compare_result _bc_do_compare(bc_num n1, bc_num n2, size_t scale, bool use_sign)
{
- char *n1ptr, *n2ptr;
-
/* First, compare signs. */
if (use_sign && n1->n_sign != n2->n_sign) {
/*
@@ -91,8 +89,8 @@ bcmath_compare_result _bc_do_compare(bc_num n1, bc_num n2, size_t scale, bool us
/* If we get here, they have the same number of integer digits.
check the integer part and the equal length part of the fraction. */
size_t count = n1->n_len + MIN (n1_scale, n2_scale);
- n1ptr = n1->n_value;
- n2ptr = n2->n_value;
+ const char *n1ptr = n1->n_value;
+ const char *n2ptr = n2->n_value;
while ((count > 0) && (*n1ptr == *n2ptr)) {
n1ptr++;
diff --git a/ext/bcmath/libbcmath/src/div.c b/ext/bcmath/libbcmath/src/div.c
index 1cf8a434c8608..24ec9a64d77fc 100644
--- a/ext/bcmath/libbcmath/src/div.c
+++ b/ext/bcmath/libbcmath/src/div.c
@@ -70,7 +70,7 @@ static inline void bc_fast_div(
*/
static inline void bc_standard_div(
BC_VECTOR *numerator_vectors, size_t numerator_arr_size,
- BC_VECTOR *divisor_vectors, size_t divisor_arr_size, size_t divisor_len,
+ const BC_VECTOR *divisor_vectors, size_t divisor_arr_size, size_t divisor_len,
BC_VECTOR *quot_vectors, size_t quot_arr_size
) {
size_t numerator_top_index = numerator_arr_size - 1;
@@ -354,10 +354,10 @@ bool bc_divide(bc_num numerator, bc_num divisor, bc_num *quot, size_t scale)
return true;
}
- char *numeratorptr = numerator->n_value;
+ const char *numeratorptr = numerator->n_value;
size_t numerator_size = numerator->n_len + quot_scale + divisor->n_scale;
- char *divisorptr = divisor->n_value;
+ const char *divisorptr = divisor->n_value;
size_t divisor_size = divisor->n_len + divisor->n_scale;
/* check and remove numerator leading zeros */
diff --git a/ext/bcmath/libbcmath/src/doaddsub.c b/ext/bcmath/libbcmath/src/doaddsub.c
index feb50120c70c3..f516f2bda72df 100644
--- a/ext/bcmath/libbcmath/src/doaddsub.c
+++ b/ext/bcmath/libbcmath/src/doaddsub.c
@@ -46,7 +46,7 @@ bc_num _bc_do_add(bc_num n1, bc_num n2)
size_t min_len = MIN (n1->n_len, n2->n_len);
size_t min_scale = MIN(n1->n_scale, n2->n_scale);
size_t min_bytes = min_len + min_scale;
- char *n1ptr, *n2ptr, *sumptr;
+ char *sumptr;
bool carry = 0;
size_t count;
@@ -54,8 +54,8 @@ bc_num _bc_do_add(bc_num n1, bc_num n2)
sum = bc_new_num_nonzeroed(sum_len, sum_scale);
/* Start with the fraction part. Initialize the pointers. */
- n1ptr = (char *) (n1->n_value + n1->n_len + n1->n_scale - 1);
- n2ptr = (char *) (n2->n_value + n2->n_len + n2->n_scale - 1);
+ const char *n1ptr = (char *) (n1->n_value + n1->n_len + n1->n_scale - 1);
+ const char *n2ptr = (char *) (n2->n_value + n2->n_len + n2->n_scale - 1);
sumptr = (char *) (sum->n_value + sum_scale + sum_len - 1);
/* Add the fraction part. First copy the longer fraction.*/
@@ -182,14 +182,14 @@ bc_num _bc_do_sub(bc_num n1, bc_num n2)
size_t borrow = 0;
size_t count;
int val;
- char *n1ptr, *n2ptr, *diffptr;
+ char *diffptr;
/* Allocate temporary storage. */
diff = bc_new_num_nonzeroed(diff_len, diff_scale);
/* Initialize the subtract. */
- n1ptr = (char *) (n1->n_value + n1->n_len + n1->n_scale - 1);
- n2ptr = (char *) (n2->n_value + n2->n_len + n2->n_scale - 1);
+ const char *n1ptr = (char *) (n1->n_value + n1->n_len + n1->n_scale - 1);
+ const char *n2ptr = (char *) (n2->n_value + n2->n_len + n2->n_scale - 1);
diffptr = (char *) (diff->n_value + diff_len + diff_scale - 1);
/* Take care of the longer scaled number. */
| diff --git a/ext/bcmath/bcmath.c b/ext/bcmath/bcmath.c
index 962f839ba83f4..1e0e6d14d81eb 100644
--- a/ext/bcmath/bcmath.c
+++ b/ext/bcmath/bcmath.c
@@ -1164,7 +1164,7 @@ static zend_always_inline bcmath_number_obj_t *bcmath_number_new_obj(bc_num ret,
return intern;
}
-static zend_result bcmath_number_parse_num(zval *zv, zend_object **obj, zend_string **str, zend_long *lval)
+static zend_result bcmath_number_parse_num(const zval *zv, zend_object **obj, zend_string **str, zend_long *lval)
if (Z_TYPE_P(zv) == IS_OBJECT && instanceof_function(Z_OBJCE_P(zv), bcmath_number_ce)) {
*obj = Z_OBJ_P(zv);
@@ -1372,7 +1372,7 @@ static int bcmath_number_compare(zval *op1, zval *op2)
}
static zend_always_inline zend_result bc_num_from_obj_or_str_or_long_with_err(
- bc_num *num, size_t *scale, zend_object *obj, zend_string *str, zend_long lval, uint32_t arg_num)
+ bc_num *num, size_t *scale, const zend_object *obj, const zend_string *str, zend_long lval, uint32_t arg_num)
size_t full_scale = 0;
if (UNEXPECTED(bc_num_from_obj_or_str_or_long(num, &full_scale, obj, str, lval) == FAILURE)) {
diff --git a/ext/bcmath/libbcmath/src/compare.c b/ext/bcmath/libbcmath/src/compare.c
index 2c24dab777059..06ef246782089 100644
--- a/ext/bcmath/libbcmath/src/compare.c
+++ b/ext/bcmath/libbcmath/src/compare.c
@@ -41,8 +41,6 @@
bcmath_compare_result _bc_do_compare(bc_num n1, bc_num n2, size_t scale, bool use_sign)
- char *n1ptr, *n2ptr;
-
/* First, compare signs. */
if (use_sign && n1->n_sign != n2->n_sign) {
/*
@@ -91,8 +89,8 @@ bcmath_compare_result _bc_do_compare(bc_num n1, bc_num n2, size_t scale, bool us
/* If we get here, they have the same number of integer digits.
check the integer part and the equal length part of the fraction. */
size_t count = n1->n_len + MIN (n1_scale, n2_scale);
- n1ptr = n1->n_value;
- n2ptr = n2->n_value;
+ const char *n1ptr = n1->n_value;
+ const char *n2ptr = n2->n_value;
while ((count > 0) && (*n1ptr == *n2ptr)) {
n1ptr++;
diff --git a/ext/bcmath/libbcmath/src/div.c b/ext/bcmath/libbcmath/src/div.c
index 1cf8a434c8608..24ec9a64d77fc 100644
--- a/ext/bcmath/libbcmath/src/div.c
+++ b/ext/bcmath/libbcmath/src/div.c
@@ -70,7 +70,7 @@ static inline void bc_fast_div(
*/
static inline void bc_standard_div(
BC_VECTOR *numerator_vectors, size_t numerator_arr_size,
- BC_VECTOR *divisor_vectors, size_t divisor_arr_size, size_t divisor_len,
+ const BC_VECTOR *divisor_vectors, size_t divisor_arr_size, size_t divisor_len,
BC_VECTOR *quot_vectors, size_t quot_arr_size
) {
size_t numerator_top_index = numerator_arr_size - 1;
@@ -354,10 +354,10 @@ bool bc_divide(bc_num numerator, bc_num divisor, bc_num *quot, size_t scale)
return true;
}
- char *numeratorptr = numerator->n_value;
+ const char *numeratorptr = numerator->n_value;
size_t numerator_size = numerator->n_len + quot_scale + divisor->n_scale;
+ const char *divisorptr = divisor->n_value;
size_t divisor_size = divisor->n_len + divisor->n_scale;
/* check and remove numerator leading zeros */
diff --git a/ext/bcmath/libbcmath/src/doaddsub.c b/ext/bcmath/libbcmath/src/doaddsub.c
index feb50120c70c3..f516f2bda72df 100644
--- a/ext/bcmath/libbcmath/src/doaddsub.c
+++ b/ext/bcmath/libbcmath/src/doaddsub.c
@@ -46,7 +46,7 @@ bc_num _bc_do_add(bc_num n1, bc_num n2)
size_t min_len = MIN (n1->n_len, n2->n_len);
size_t min_scale = MIN(n1->n_scale, n2->n_scale);
size_t min_bytes = min_len + min_scale;
- char *n1ptr, *n2ptr, *sumptr;
+ char *sumptr;
bool carry = 0;
@@ -54,8 +54,8 @@ bc_num _bc_do_add(bc_num n1, bc_num n2)
sum = bc_new_num_nonzeroed(sum_len, sum_scale);
/* Start with the fraction part. Initialize the pointers. */
sumptr = (char *) (sum->n_value + sum_scale + sum_len - 1);
/* Add the fraction part. First copy the longer fraction.*/
@@ -182,14 +182,14 @@ bc_num _bc_do_sub(bc_num n1, bc_num n2)
size_t borrow = 0;
int val;
- char *n1ptr, *n2ptr, *diffptr;
+ char *diffptr;
/* Allocate temporary storage. */
diff = bc_new_num_nonzeroed(diff_len, diff_scale);
/* Initialize the subtract. */
diffptr = (char *) (diff->n_value + diff_len + diff_scale - 1);
/* Take care of the longer scaled number. */ | [
"-\tchar *divisorptr = divisor->n_value;"
] | [
67
] | {
"additions": 13,
"author": "SakiTakamachi",
"deletions": 15,
"html_url": "https://github.com/php/php-src/pull/18284",
"issue_id": 18284,
"merged_at": "2025-04-11T03:39:31Z",
"omission_probability": 0.1,
"pr_number": 18284,
"repo": "php/php-src",
"title": "ext/bcmath: Use `const` qualifiers appropriately",
"total_changes": 28
} |
760 | diff --git a/UPGRADING b/UPGRADING
index 6cc0cc537df2d..451cfe4b86b3e 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -147,6 +147,11 @@ PHP 8.5 UPGRADE NOTES
indicating the http and proxy authentication methods that were
used in the previous request. See CURLAUTH_* constants for
possible values.
+ . Added CURLOPT_INFILESIZE_LARGE Curl option, which is a safe
+ replacement for CURLOPT_INFILESIZE. On certain systems,
+ CURLOPT_INFILESIZE only accepts a 32-bit signed integer as the file
+ size (2.0 GiB) even on 64-bit systems. CURLOPT_INFILESIZE_LARGE
+ accepts the largest integer value the system can handle.
- DOM:
. Added Dom\Element::$outerHTML.
@@ -343,6 +348,7 @@ PHP 8.5 UPGRADE NOTES
. CURLINFO_USED_PROXY.
. CURLINFO_HTTPAUTH_USED.
. CURLINFO_PROXYAUTH_USED.
+ . CURLOPT_INFILESIZE_LARGE.
- Intl:
. DECIMAL_COMPACT_SHORT.
diff --git a/ext/curl/curl.stub.php b/ext/curl/curl.stub.php
index c9abe237339b5..6a73913f8a85e 100644
--- a/ext/curl/curl.stub.php
+++ b/ext/curl/curl.stub.php
@@ -188,6 +188,11 @@
* @cvalue CURLOPT_INFILESIZE
*/
const CURLOPT_INFILESIZE = UNKNOWN;
+/**
+ * @var int
+ * @cvalue CURLOPT_INFILESIZE_LARGE
+ */
+const CURLOPT_INFILESIZE_LARGE = UNKNOWN;
/**
* @var int
* @cvalue CURLOPT_INTERFACE
diff --git a/ext/curl/curl_arginfo.h b/ext/curl/curl_arginfo.h
index 6a81d1e92c88f..53a59fe47be49 100644
--- a/ext/curl/curl_arginfo.h
+++ b/ext/curl/curl_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: 48fc95503f4f8cc96575ff6f31fdd1e4cdc5969e */
+ * Stub hash: 77da3a34f08b3e932a0545f72b41bf0353e8b157 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_curl_close, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, handle, CurlHandle, 0)
@@ -263,6 +263,7 @@ static void register_curl_symbols(int module_number)
REGISTER_LONG_CONSTANT("CURLOPT_HTTP_VERSION", CURLOPT_HTTP_VERSION, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_INFILE", CURLOPT_INFILE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_INFILESIZE", CURLOPT_INFILESIZE, CONST_PERSISTENT);
+ REGISTER_LONG_CONSTANT("CURLOPT_INFILESIZE_LARGE", CURLOPT_INFILESIZE_LARGE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_INTERFACE", CURLOPT_INTERFACE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_KRB4LEVEL", CURLOPT_KRB4LEVEL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_LOW_SPEED_LIMIT", CURLOPT_LOW_SPEED_LIMIT, CONST_PERSISTENT);
diff --git a/ext/curl/interface.c b/ext/curl/interface.c
index aebb336378bc0..8458cd77dabd2 100644
--- a/ext/curl/interface.c
+++ b/ext/curl/interface.c
@@ -2244,6 +2244,7 @@ static zend_result _php_curl_setopt(php_curl *ch, zend_long option, zval *zvalue
break;
/* Curl off_t options */
+ case CURLOPT_INFILESIZE_LARGE:
case CURLOPT_MAX_RECV_SPEED_LARGE:
case CURLOPT_MAX_SEND_SPEED_LARGE:
case CURLOPT_MAXFILESIZE_LARGE:
diff --git a/ext/curl/tests/Caddyfile b/ext/curl/tests/Caddyfile
index 30686f0bb9fa2..67b82434ba4c6 100644
--- a/ext/curl/tests/Caddyfile
+++ b/ext/curl/tests/Caddyfile
@@ -12,6 +12,11 @@ respond /serverpush "main response"
respond /serverpush/pushed "pushed response"
push /serverpush /serverpush/pushed
+route /show_upload_size {
+ templates
+ respond `Content-length: ={{.Req.Header.Get "Content-length"}}=`
+}
+
basic_auth /http-basic-auth {
# bcrypt password hash for "password", calculated with 'caddy hash-password'
user $2a$14$yUKl9SGqVTAAqPTzLup.DefsbXXx3kfreNnzpJOUHcIrKnr5lgef2
diff --git a/ext/curl/tests/curl_setopt_CURLOPT_INFILESIZE_LARGE.phpt b/ext/curl/tests/curl_setopt_CURLOPT_INFILESIZE_LARGE.phpt
new file mode 100644
index 0000000000000..5063958412b5a
--- /dev/null
+++ b/ext/curl/tests/curl_setopt_CURLOPT_INFILESIZE_LARGE.phpt
@@ -0,0 +1,58 @@
+--TEST--
+Curl option CURLOPT_INFILESIZE_LARGE
+--EXTENSIONS--
+curl
+--SKIPIF--
+<?php
+include 'skipif-nocaddy.inc';
+?>
+--FILE--
+<?php
+$ch = curl_init("https://localhost/show_upload_size");
+$f = fopen(__FILE__,"r");
+var_dump(curl_setopt_array($ch, [
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_UPLOAD => true,
+ CURLOPT_INFILE => $f,
+ CURLOPT_INFILESIZE => filesize(__FILE__),
+ CURLOPT_CONNECTTIMEOUT => 3,
+ CURLOPT_TIMEOUT => 3,
+ CURLOPT_SSL_VERIFYHOST => 0,
+ CURLOPT_SSL_VERIFYPEER => 0,
+]));
+
+var_dump(curl_exec($ch));
+
+var_dump(curl_setopt($ch, CURLOPT_INFILESIZE, -1));
+var_dump(curl_exec($ch));
+
+var_dump(curl_setopt($ch, CURLOPT_INFILESIZE_LARGE, -1));
+var_dump(curl_exec($ch));
+
+rewind($f);
+var_dump(curl_setopt($ch, CURLOPT_INFILESIZE, filesize(__FILE__)));
+var_dump(curl_exec($ch));
+var_dump(curl_setopt($ch, CURLOPT_INFILESIZE_LARGE, -1));
+var_dump(curl_exec($ch));
+
+rewind($f);
+var_dump(curl_setopt($ch, CURLOPT_INFILESIZE_LARGE, filesize(__FILE__)));
+var_dump(curl_exec($ch));
+
+var_dump(curl_error($ch));
+
+?>
+--EXPECTF--
+bool(true)
+string(21) "Content-length: =%d="
+bool(true)
+string(18) "Content-length: =="
+bool(true)
+string(18) "Content-length: =="
+bool(true)
+string(21) "Content-length: =%d="
+bool(true)
+string(18) "Content-length: =="
+bool(true)
+string(21) "Content-length: =%d="
+string(0) ""
| diff --git a/UPGRADING b/UPGRADING
index 6cc0cc537df2d..451cfe4b86b3e 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -147,6 +147,11 @@ PHP 8.5 UPGRADE NOTES
indicating the http and proxy authentication methods that were
used in the previous request. See CURLAUTH_* constants for
possible values.
+ . Added CURLOPT_INFILESIZE_LARGE Curl option, which is a safe
+ replacement for CURLOPT_INFILESIZE. On certain systems,
+ CURLOPT_INFILESIZE only accepts a 32-bit signed integer as the file
+ size (2.0 GiB) even on 64-bit systems. CURLOPT_INFILESIZE_LARGE
+ accepts the largest integer value the system can handle.
- DOM:
. Added Dom\Element::$outerHTML.
@@ -343,6 +348,7 @@ PHP 8.5 UPGRADE NOTES
. CURLINFO_USED_PROXY.
. CURLINFO_HTTPAUTH_USED.
. CURLINFO_PROXYAUTH_USED.
+ . CURLOPT_INFILESIZE_LARGE.
- Intl:
. DECIMAL_COMPACT_SHORT.
diff --git a/ext/curl/curl.stub.php b/ext/curl/curl.stub.php
index c9abe237339b5..6a73913f8a85e 100644
--- a/ext/curl/curl.stub.php
+++ b/ext/curl/curl.stub.php
@@ -188,6 +188,11 @@
* @cvalue CURLOPT_INFILESIZE
*/
const CURLOPT_INFILESIZE = UNKNOWN;
+ * @var int
+ * @cvalue CURLOPT_INFILESIZE_LARGE
+ */
+const CURLOPT_INFILESIZE_LARGE = UNKNOWN;
/**
* @var int
* @cvalue CURLOPT_INTERFACE
diff --git a/ext/curl/curl_arginfo.h b/ext/curl/curl_arginfo.h
index 6a81d1e92c88f..53a59fe47be49 100644
--- a/ext/curl/curl_arginfo.h
+++ b/ext/curl/curl_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: 48fc95503f4f8cc96575ff6f31fdd1e4cdc5969e */
+ * Stub hash: 77da3a34f08b3e932a0545f72b41bf0353e8b157 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_curl_close, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, handle, CurlHandle, 0)
@@ -263,6 +263,7 @@ static void register_curl_symbols(int module_number)
REGISTER_LONG_CONSTANT("CURLOPT_HTTP_VERSION", CURLOPT_HTTP_VERSION, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_INFILE", CURLOPT_INFILE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_INFILESIZE", CURLOPT_INFILESIZE, CONST_PERSISTENT);
+ REGISTER_LONG_CONSTANT("CURLOPT_INFILESIZE_LARGE", CURLOPT_INFILESIZE_LARGE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_INTERFACE", CURLOPT_INTERFACE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_KRB4LEVEL", CURLOPT_KRB4LEVEL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CURLOPT_LOW_SPEED_LIMIT", CURLOPT_LOW_SPEED_LIMIT, CONST_PERSISTENT);
diff --git a/ext/curl/interface.c b/ext/curl/interface.c
index aebb336378bc0..8458cd77dabd2 100644
--- a/ext/curl/interface.c
+++ b/ext/curl/interface.c
@@ -2244,6 +2244,7 @@ static zend_result _php_curl_setopt(php_curl *ch, zend_long option, zval *zvalue
break;
/* Curl off_t options */
+ case CURLOPT_INFILESIZE_LARGE:
case CURLOPT_MAX_RECV_SPEED_LARGE:
case CURLOPT_MAX_SEND_SPEED_LARGE:
case CURLOPT_MAXFILESIZE_LARGE:
diff --git a/ext/curl/tests/Caddyfile b/ext/curl/tests/Caddyfile
index 30686f0bb9fa2..67b82434ba4c6 100644
--- a/ext/curl/tests/Caddyfile
+++ b/ext/curl/tests/Caddyfile
@@ -12,6 +12,11 @@ respond /serverpush "main response"
respond /serverpush/pushed "pushed response"
push /serverpush /serverpush/pushed
+route /show_upload_size {
+ templates
+ respond `Content-length: ={{.Req.Header.Get "Content-length"}}=`
+}
basic_auth /http-basic-auth {
# bcrypt password hash for "password", calculated with 'caddy hash-password'
user $2a$14$yUKl9SGqVTAAqPTzLup.DefsbXXx3kfreNnzpJOUHcIrKnr5lgef2
diff --git a/ext/curl/tests/curl_setopt_CURLOPT_INFILESIZE_LARGE.phpt b/ext/curl/tests/curl_setopt_CURLOPT_INFILESIZE_LARGE.phpt
new file mode 100644
index 0000000000000..5063958412b5a
--- /dev/null
+++ b/ext/curl/tests/curl_setopt_CURLOPT_INFILESIZE_LARGE.phpt
@@ -0,0 +1,58 @@
+--TEST--
+Curl option CURLOPT_INFILESIZE_LARGE
+--EXTENSIONS--
+curl
+include 'skipif-nocaddy.inc';
+--FILE--
+$ch = curl_init("https://localhost/show_upload_size");
+var_dump(curl_setopt_array($ch, [
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_UPLOAD => true,
+ CURLOPT_INFILE => $f,
+ CURLOPT_CONNECTTIMEOUT => 3,
+ CURLOPT_TIMEOUT => 3,
+ CURLOPT_SSL_VERIFYHOST => 0,
+var_dump(curl_setopt($ch, CURLOPT_INFILESIZE, -1));
+var_dump(curl_setopt($ch, CURLOPT_INFILESIZE, filesize(__FILE__)));
+var_dump(curl_setopt($ch, CURLOPT_INFILESIZE_LARGE, filesize(__FILE__)));
+var_dump(curl_error($ch));
+--EXPECTF--
+string(0) "" | [
"+/**",
"+--SKIPIF--",
"+$f = fopen(__FILE__,\"r\");",
"+ CURLOPT_INFILESIZE => filesize(__FILE__),",
"+ CURLOPT_SSL_VERIFYPEER => 0,",
"+]));"
] | [
32,
97,
104,
109,
113,
114
] | {
"additions": 77,
"author": "OskarStark",
"deletions": 1,
"html_url": "https://github.com/php/php-src/pull/17637",
"issue_id": 17637,
"merged_at": "2025-04-09T07:12:14Z",
"omission_probability": 0.1,
"pr_number": 17637,
"repo": "php/php-src",
"title": "[ext-curl] Add `\\CURLOPT_INFILESIZE_LARGE`",
"total_changes": 78
} |
761 | diff --git a/ext/fileinfo/fileinfo.c b/ext/fileinfo/fileinfo.c
index d3680c5755f25..c0cc8877bf991 100644
--- a/ext/fileinfo/fileinfo.c
+++ b/ext/fileinfo/fileinfo.c
@@ -344,6 +344,9 @@ PHP_FUNCTION(finfo_file)
RETURN_THROWS();
}
php_stream_context *context = php_stream_context_from_zval(zcontext, false);
+ if (!context) {
+ RETURN_THROWS();
+ }
/* Set options for the current file/buffer. */
if (options) {
diff --git a/ext/fileinfo/tests/gh18267.phpt b/ext/fileinfo/tests/gh18267.phpt
new file mode 100644
index 0000000000000..ba7647288d1de
--- /dev/null
+++ b/ext/fileinfo/tests/gh18267.phpt
@@ -0,0 +1,14 @@
+--TEST--
+GH-18267 finfo_file() assertion trigger on NULL stream context
+--EXTENSIONS--
+fileinfo
+--FILE--
+<?php
+$cls = new finfo();
+try {
+ $cls->file("test",FILEINFO_NONE, STDERR);
+} catch (\TypeError $e) {
+ echo $e->getMessage();
+}
+--EXPECT--
+finfo::file(): supplied resource is not a valid Stream-Context resource
| diff --git a/ext/fileinfo/fileinfo.c b/ext/fileinfo/fileinfo.c
index d3680c5755f25..c0cc8877bf991 100644
--- a/ext/fileinfo/fileinfo.c
+++ b/ext/fileinfo/fileinfo.c
@@ -344,6 +344,9 @@ PHP_FUNCTION(finfo_file)
RETURN_THROWS();
}
php_stream_context *context = php_stream_context_from_zval(zcontext, false);
+ if (!context) {
+ RETURN_THROWS();
/* Set options for the current file/buffer. */
if (options) {
diff --git a/ext/fileinfo/tests/gh18267.phpt b/ext/fileinfo/tests/gh18267.phpt
new file mode 100644
index 0000000000000..ba7647288d1de
--- /dev/null
+++ b/ext/fileinfo/tests/gh18267.phpt
@@ -0,0 +1,14 @@
+--TEST--
+GH-18267 finfo_file() assertion trigger on NULL stream context
+--EXTENSIONS--
+fileinfo
+$cls = new finfo();
+try {
+ $cls->file("test",FILEINFO_NONE, STDERR);
+} catch (\TypeError $e) {
+ echo $e->getMessage();
+}
+--EXPECT--
+finfo::file(): supplied resource is not a valid Stream-Context resource | [
"+\t}",
"+--FILE--",
"+<?php"
] | [
10,
24,
25
] | {
"additions": 17,
"author": "devnexen",
"deletions": 0,
"html_url": "https://github.com/php/php-src/pull/18269",
"issue_id": 18269,
"merged_at": "2025-04-08T21:43:11Z",
"omission_probability": 0.1,
"pr_number": 18269,
"repo": "php/php-src",
"title": "Fixed GH-18267 finfo_file() crashing on invalid URL protocol.",
"total_changes": 17
} |
762 | diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index acd9c1220c20e..f0f80bd98e324 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -22,15 +22,22 @@ body:
```
validations:
required: true
- - type: input
+ - type: textarea
attributes:
label: PHP Version
- description: "The used PHP version. Make sure it is [supported](https://www.php.net/supported-versions.php)."
- placeholder: "PHP 8.0.12"
+ description: |
+ Please run PHP with the `-v` flag (e.g. `php -v`, `php8.3 -v`, `php-fpm -v` or similar) and provide the full output of that command. If executing that command is not possible, please provide the full version number as given in PHPInfo.
+
+ Please make sure that the used PHP version [is a supported version](https://www.php.net/supported-versions.php).
+ placeholder: |
+ PHP 8.3.19 (cli) (built: Mar 13 2025 17:44:40) (NTS)
+ Copyright (c) The PHP Group
+ Zend Engine v4.3.19, Copyright (c) Zend Technologies
+ with Zend OPcache v8.3.19, Copyright (c), by Zend Technologies
validations:
required: true
- type: input
attributes:
label: Operating System
description: "The used operating system, if relevant."
- placeholder: "Ubuntu 20.04"
+ placeholder: "Ubuntu 24.04"
| diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index acd9c1220c20e..f0f80bd98e324 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -22,15 +22,22 @@ body:
```
+ - type: textarea
label: PHP Version
- description: "The used PHP version. Make sure it is [supported](https://www.php.net/supported-versions.php)."
- placeholder: "PHP 8.0.12"
+ description: |
+ Please run PHP with the `-v` flag (e.g. `php -v`, `php8.3 -v`, `php-fpm -v` or similar) and provide the full output of that command. If executing that command is not possible, please provide the full version number as given in PHPInfo.
+
+ Please make sure that the used PHP version [is a supported version](https://www.php.net/supported-versions.php).
+ placeholder: |
+ PHP 8.3.19 (cli) (built: Mar 13 2025 17:44:40) (NTS)
+ Copyright (c) The PHP Group
+ Zend Engine v4.3.19, Copyright (c) Zend Technologies
+ with Zend OPcache v8.3.19, Copyright (c), by Zend Technologies
- type: input
label: Operating System
description: "The used operating system, if relevant."
- placeholder: "Ubuntu 20.04"
+ placeholder: "Ubuntu 24.04" | [
"- - type: input"
] | [
8
] | {
"additions": 11,
"author": "TimWolla",
"deletions": 4,
"html_url": "https://github.com/php/php-src/pull/18230",
"issue_id": 18230,
"merged_at": "2025-04-07T08:51:30Z",
"omission_probability": 0.1,
"pr_number": 18230,
"repo": "php/php-src",
"title": "[skip ci] Request the output of `php -v` in the `bug_report.yml` issue template",
"total_changes": 15
} |
763 | diff --git a/Zend/tests/attributes/nodiscard/005.phpt b/Zend/tests/attributes/nodiscard/005.phpt
index ec8f33e5299d6..9ef1566372892 100644
--- a/Zend/tests/attributes/nodiscard/005.phpt
+++ b/Zend/tests/attributes/nodiscard/005.phpt
@@ -1,17 +1,11 @@
--TEST--
-#[\NoDiscard]: Native function and method.
+#[\NoDiscard]: Native method.
--FILE--
<?php
-$f = tmpfile();
-flock($f, LOCK_SH | LOCK_NB);
-fclose($f);
-
$date = new DateTimeImmutable('now');
$date->setTimestamp(0);
?>
--EXPECTF--
-Warning: The return value of function flock() should either be used or intentionally ignored by casting it as (void), as locking the stream might have failed in %s on line %d
-
Warning: The return value of method DateTimeImmutable::setTimestamp() should either be used or intentionally ignored by casting it as (void), as DateTimeImmutable::setTimestamp() does not modify the object itself in %s on line %d
diff --git a/Zend/tests/attributes/nodiscard/007.phpt b/Zend/tests/attributes/nodiscard/007.phpt
index 84dff0c8e44f6..1b72de8c22a06 100644
--- a/Zend/tests/attributes/nodiscard/007.phpt
+++ b/Zend/tests/attributes/nodiscard/007.phpt
@@ -7,15 +7,11 @@ zend_test.observer.execute_internal=1
--FILE--
<?php
-$f = tmpfile();
-flock($f, LOCK_SH | LOCK_NB);
-fclose($f);
+zend_test_nodiscard();
?>
--EXPECTF--
-<!-- internal enter tmpfile() -->
<!-- internal enter NoDiscard::__construct() -->
-Warning: The return value of function flock() should either be used or intentionally ignored by casting it as (void), as locking the stream might have failed in %s on line %d
-<!-- internal enter flock() -->
-<!-- internal enter fclose() -->
+Warning: The return value of function zend_test_nodiscard() should either be used or intentionally ignored by casting it as (void), custom message in %s on line %d
+<!-- internal enter zend_test_nodiscard() -->
diff --git a/Zend/tests/attributes/nodiscard/010.phpt b/Zend/tests/attributes/nodiscard/010.phpt
new file mode 100644
index 0000000000000..5534fc3404da9
--- /dev/null
+++ b/Zend/tests/attributes/nodiscard/010.phpt
@@ -0,0 +1,12 @@
+--TEST--
+#[\NoDiscard]: Native function.
+--EXTENSIONS--
+zend_test
+--FILE--
+<?php
+
+zend_test_nodiscard();
+
+?>
+--EXPECTF--
+Warning: The return value of function zend_test_nodiscard() should either be used or intentionally ignored by casting it as (void), custom message in %s on line %d
diff --git a/ext/opcache/tests/nodiscard_001.phpt b/ext/opcache/tests/nodiscard_001.phpt
index f4f7b8488e98a..7e232f8f44e41 100644
--- a/ext/opcache/tests/nodiscard_001.phpt
+++ b/ext/opcache/tests/nodiscard_001.phpt
@@ -7,14 +7,13 @@ opcache.optimization_level=-1
opcache.opt_debug_level=0x20000
--EXTENSIONS--
opcache
+zend_test
--FILE--
<?php
-$f = tmpfile();
-flock($f, LOCK_SH | LOCK_NB);
-(void)flock($f, LOCK_SH | LOCK_NB);
-$success = flock($f, LOCK_SH | LOCK_NB);
-fclose($f);
+zend_test_nodiscard();
+(void)zend_test_nodiscard();
+$success = zend_test_nodiscard();
#[\NoDiscard]
function test() {
@@ -28,38 +27,26 @@ $obj = test();
?>
--EXPECTF--
$_main:
- ; (lines=29, args=0, vars=3, tmps=%d)
+ ; (lines=17, args=0, vars=2, tmps=%d)
; (after optimizer)
; %s
-0000 INIT_FCALL 0 %d string("tmpfile")
-0001 V3 = DO_ICALL
-0002 ASSIGN CV0($f) V3
-0003 INIT_FCALL 2 %d string("flock")
-0004 SEND_VAR CV0($f) 1
-0005 SEND_VAL int(5) 2
-0006 DO_FCALL_BY_NAME
-0007 INIT_FCALL 2 %d string("flock")
-0008 SEND_VAR CV0($f) 1
-0009 SEND_VAL int(5) 2
-0010 V3 = DO_ICALL
-0011 FREE V3
-0012 INIT_FCALL 2 %d string("flock")
-0013 SEND_VAR CV0($f) 1
-0014 SEND_VAL int(5) 2
-0015 V3 = DO_ICALL
-0016 ASSIGN CV1($success) V3
-0017 INIT_FCALL 1 %d string("fclose")
-0018 SEND_VAR CV0($f) 1
-0019 DO_ICALL
-0020 INIT_FCALL 0 %d string("test")
-0021 DO_FCALL_BY_NAME
-0022 INIT_FCALL 0 %d string("test")
-0023 V3 = DO_UCALL
-0024 FREE V3
-0025 INIT_FCALL 0 %d string("test")
-0026 V3 = DO_UCALL
-0027 ASSIGN CV2($obj) V3
-0028 RETURN int(1)
+0000 INIT_FCALL 0 %d string("zend_test_nodiscard")
+0001 DO_FCALL_BY_NAME
+0002 INIT_FCALL 0 %d string("zend_test_nodiscard")
+0003 V2 = DO_ICALL
+0004 FREE V2
+0005 INIT_FCALL 0 %d string("zend_test_nodiscard")
+0006 V2 = DO_ICALL
+0007 ASSIGN CV0($success) V2
+0008 INIT_FCALL 0 %d string("test")
+0009 DO_FCALL_BY_NAME
+0010 INIT_FCALL 0 %d string("test")
+0011 V2 = DO_UCALL
+0012 FREE V2
+0013 INIT_FCALL 0 %d string("test")
+0014 V2 = DO_UCALL
+0015 ASSIGN CV1($obj) V2
+0016 RETURN int(1)
test:
; (lines=3, args=0, vars=0, tmps=%d)
@@ -71,6 +58,6 @@ test:
LIVE RANGES:
0: 0001 - 0002 (new)
-Warning: The return value of function flock() should either be used or intentionally ignored by casting it as (void), as locking the stream might have failed in %s on line %d
+Warning: The return value of function zend_test_nodiscard() should either be used or intentionally ignored by casting it as (void), custom message in %s on line %d
Warning: The return value of function test() should either be used or intentionally ignored by casting it as (void) in %s on line %d
diff --git a/ext/standard/basic_functions.stub.php b/ext/standard/basic_functions.stub.php
index b6533d8dc20e8..e7f4ff8844714 100644
--- a/ext/standard/basic_functions.stub.php
+++ b/ext/standard/basic_functions.stub.php
@@ -2732,7 +2732,6 @@ function proc_nice(int $priority): bool {}
* @param resource $stream
* @param int $would_block
*/
-#[\NoDiscard(message: "as locking the stream might have failed")]
function flock($stream, int $operation, &$would_block = null): bool {}
/**
diff --git a/ext/standard/basic_functions_arginfo.h b/ext/standard/basic_functions_arginfo.h
index d35377c900735..3d92288643159 100644
--- a/ext/standard/basic_functions_arginfo.h
+++ b/ext/standard/basic_functions_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: 824ccb41163307bd0fad452b705a8222b6f42d09 */
+ * Stub hash: 85677dc3476d25b7820fd3a26fe39f2e9378b6e7 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_set_time_limit, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, seconds, IS_LONG, 0)
@@ -3205,7 +3205,7 @@ static const zend_function_entry ext_functions[] = {
#if defined(HAVE_NICE)
ZEND_FE(proc_nice, arginfo_proc_nice)
#endif
- ZEND_RAW_FENTRY("flock", zif_flock, arginfo_flock, ZEND_ACC_NODISCARD, NULL, NULL)
+ ZEND_FE(flock, arginfo_flock)
ZEND_FE(get_meta_tags, arginfo_get_meta_tags)
ZEND_FE(pclose, arginfo_pclose)
ZEND_FE(popen, arginfo_popen)
@@ -4039,15 +4039,6 @@ static void register_basic_functions_symbols(int module_number)
ZVAL_COPY_VALUE(&attribute_Deprecated_func_utf8_decode_0->args[1].value, &attribute_Deprecated_func_utf8_decode_0_arg1);
attribute_Deprecated_func_utf8_decode_0->args[1].name = ZSTR_KNOWN(ZEND_STR_MESSAGE);
- zend_string *attribute_name_NoDiscard_func_flock_0 = zend_string_init_interned("NoDiscard", sizeof("NoDiscard") - 1, 1);
- zend_attribute *attribute_NoDiscard_func_flock_0 = zend_add_function_attribute(zend_hash_str_find_ptr(CG(function_table), "flock", sizeof("flock") - 1), attribute_name_NoDiscard_func_flock_0, 1);
- zend_string_release(attribute_name_NoDiscard_func_flock_0);
- zval attribute_NoDiscard_func_flock_0_arg0;
- zend_string *attribute_NoDiscard_func_flock_0_arg0_str = zend_string_init("as locking the stream might have failed", strlen("as locking the stream might have failed"), 1);
- ZVAL_STR(&attribute_NoDiscard_func_flock_0_arg0, attribute_NoDiscard_func_flock_0_arg0_str);
- ZVAL_COPY_VALUE(&attribute_NoDiscard_func_flock_0->args[0].value, &attribute_NoDiscard_func_flock_0_arg0);
- attribute_NoDiscard_func_flock_0->args[0].name = ZSTR_KNOWN(ZEND_STR_MESSAGE);
-
zend_add_parameter_attribute(zend_hash_str_find_ptr(CG(function_table), "password_hash", sizeof("password_hash") - 1), 0, ZSTR_KNOWN(ZEND_STR_SENSITIVEPARAMETER), 0);
zend_add_parameter_attribute(zend_hash_str_find_ptr(CG(function_table), "password_verify", sizeof("password_verify") - 1), 0, ZSTR_KNOWN(ZEND_STR_SENSITIVEPARAMETER), 0);
diff --git a/ext/zend_test/test.c b/ext/zend_test/test.c
index b9190f6753052..ba18639aead82 100644
--- a/ext/zend_test/test.c
+++ b/ext/zend_test/test.c
@@ -124,6 +124,13 @@ static ZEND_FUNCTION(zend_test_deprecated_attr)
ZEND_PARSE_PARAMETERS_NONE();
}
+static ZEND_FUNCTION(zend_test_nodiscard)
+{
+ ZEND_PARSE_PARAMETERS_NONE();
+
+ RETURN_LONG(1);
+}
+
static ZEND_FUNCTION(zend_test_deprecated_nodiscard)
{
ZEND_PARSE_PARAMETERS_NONE();
diff --git a/ext/zend_test/test.stub.php b/ext/zend_test/test.stub.php
index 921dadd00ce15..10272c51cad49 100644
--- a/ext/zend_test/test.stub.php
+++ b/ext/zend_test/test.stub.php
@@ -218,6 +218,8 @@ function zend_test_deprecated(mixed $arg = null): void {}
#[\Deprecated(message: "custom message")]
function zend_test_deprecated_attr(): void {}
+ #[\NoDiscard(message: "custom message")]
+ function zend_test_nodiscard(): int {}
#[\Deprecated(message: "custom message")]
#[\NoDiscard(message: "custom message 2")]
diff --git a/ext/zend_test/test_arginfo.h b/ext/zend_test/test_arginfo.h
index 391f2fc500b02..62b57223dac2a 100644
--- a/ext/zend_test/test_arginfo.h
+++ b/ext/zend_test/test_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: eebe535d0295f707201ff751e38a5ad3837dbbd2 */
+ * Stub hash: bedc3883fbfe2491c95375beb13140e7fcfd83a5 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_array_return, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
@@ -22,9 +22,11 @@ ZEND_END_ARG_INFO()
#define arginfo_zend_test_deprecated_attr arginfo_zend_test_void_return
-ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_deprecated_nodiscard, 0, 0, IS_LONG, 0)
+ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_nodiscard, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
+#define arginfo_zend_test_deprecated_nodiscard arginfo_zend_test_nodiscard
+
#define arginfo_zend_test_aliased arginfo_zend_test_void_return
#define arginfo_zend_test_deprecated_aliased arginfo_zend_test_void_return
@@ -131,7 +133,7 @@ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_is_string_marked_as_va
ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0)
ZEND_END_ARG_INFO()
-#define arginfo_zend_get_map_ptr_last arginfo_zend_test_deprecated_nodiscard
+#define arginfo_zend_get_map_ptr_last arginfo_zend_test_nodiscard
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_crash, 0, 0, IS_VOID, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, message, IS_STRING, 1, "null")
@@ -189,7 +191,7 @@ ZEND_END_ARG_INFO()
#define arginfo_ZendTestNS2_ZendSubNS_namespaced_deprecated_aliased_func arginfo_zend_test_void_return
-#define arginfo_class__ZendTestClass_is_object arginfo_zend_test_deprecated_nodiscard
+#define arginfo_class__ZendTestClass_is_object arginfo_zend_test_nodiscard
#define arginfo_class__ZendTestClass___toString arginfo_zend_get_current_func_name
@@ -264,6 +266,7 @@ static ZEND_FUNCTION(zend_test_void_return);
static ZEND_FUNCTION(zend_test_compile_string);
static ZEND_FUNCTION(zend_test_deprecated);
static ZEND_FUNCTION(zend_test_deprecated_attr);
+static ZEND_FUNCTION(zend_test_nodiscard);
static ZEND_FUNCTION(zend_test_deprecated_nodiscard);
static ZEND_FUNCTION(zend_create_unterminated_string);
static ZEND_FUNCTION(zend_terminate_string);
@@ -361,6 +364,11 @@ static const zend_function_entry ext_functions[] = {
#else
ZEND_RAW_FENTRY("zend_test_deprecated_attr", zif_zend_test_deprecated_attr, arginfo_zend_test_deprecated_attr, ZEND_ACC_DEPRECATED)
#endif
+#if (PHP_VERSION_ID >= 80400)
+ ZEND_RAW_FENTRY("zend_test_nodiscard", zif_zend_test_nodiscard, arginfo_zend_test_nodiscard, ZEND_ACC_NODISCARD, NULL, NULL)
+#else
+ ZEND_RAW_FENTRY("zend_test_nodiscard", zif_zend_test_nodiscard, arginfo_zend_test_nodiscard, ZEND_ACC_NODISCARD)
+#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("zend_test_deprecated_nodiscard", zif_zend_test_deprecated_nodiscard, arginfo_zend_test_deprecated_nodiscard, ZEND_ACC_DEPRECATED|ZEND_ACC_NODISCARD, NULL, NULL)
#else
@@ -572,6 +580,15 @@ static void register_test_symbols(int module_number)
ZVAL_COPY_VALUE(&attribute_Deprecated_func_zend_test_deprecated_attr_0->args[0].value, &attribute_Deprecated_func_zend_test_deprecated_attr_0_arg0);
attribute_Deprecated_func_zend_test_deprecated_attr_0->args[0].name = ZSTR_KNOWN(ZEND_STR_MESSAGE);
+ zend_string *attribute_name_NoDiscard_func_zend_test_nodiscard_0 = zend_string_init_interned("NoDiscard", sizeof("NoDiscard") - 1, 1);
+ zend_attribute *attribute_NoDiscard_func_zend_test_nodiscard_0 = zend_add_function_attribute(zend_hash_str_find_ptr(CG(function_table), "zend_test_nodiscard", sizeof("zend_test_nodiscard") - 1), attribute_name_NoDiscard_func_zend_test_nodiscard_0, 1);
+ zend_string_release(attribute_name_NoDiscard_func_zend_test_nodiscard_0);
+ zval attribute_NoDiscard_func_zend_test_nodiscard_0_arg0;
+ zend_string *attribute_NoDiscard_func_zend_test_nodiscard_0_arg0_str = zend_string_init("custom message", strlen("custom message"), 1);
+ ZVAL_STR(&attribute_NoDiscard_func_zend_test_nodiscard_0_arg0, attribute_NoDiscard_func_zend_test_nodiscard_0_arg0_str);
+ ZVAL_COPY_VALUE(&attribute_NoDiscard_func_zend_test_nodiscard_0->args[0].value, &attribute_NoDiscard_func_zend_test_nodiscard_0_arg0);
+ attribute_NoDiscard_func_zend_test_nodiscard_0->args[0].name = ZSTR_KNOWN(ZEND_STR_MESSAGE);
+
zend_string *attribute_name_Deprecated_func_zend_test_deprecated_nodiscard_0 = zend_string_init_interned("Deprecated", sizeof("Deprecated") - 1, 1);
zend_attribute *attribute_Deprecated_func_zend_test_deprecated_nodiscard_0 = zend_add_function_attribute(zend_hash_str_find_ptr(CG(function_table), "zend_test_deprecated_nodiscard", sizeof("zend_test_deprecated_nodiscard") - 1), attribute_name_Deprecated_func_zend_test_deprecated_nodiscard_0, 1);
zend_string_release(attribute_name_Deprecated_func_zend_test_deprecated_nodiscard_0);
| diff --git a/Zend/tests/attributes/nodiscard/005.phpt b/Zend/tests/attributes/nodiscard/005.phpt
index ec8f33e5299d6..9ef1566372892 100644
--- a/Zend/tests/attributes/nodiscard/005.phpt
+++ b/Zend/tests/attributes/nodiscard/005.phpt
@@ -1,17 +1,11 @@
--TEST--
-#[\NoDiscard]: Native function and method.
+#[\NoDiscard]: Native method.
$date = new DateTimeImmutable('now');
$date->setTimestamp(0);
Warning: The return value of method DateTimeImmutable::setTimestamp() should either be used or intentionally ignored by casting it as (void), as DateTimeImmutable::setTimestamp() does not modify the object itself in %s on line %d
diff --git a/Zend/tests/attributes/nodiscard/007.phpt b/Zend/tests/attributes/nodiscard/007.phpt
index 84dff0c8e44f6..1b72de8c22a06 100644
--- a/Zend/tests/attributes/nodiscard/007.phpt
+++ b/Zend/tests/attributes/nodiscard/007.phpt
@@ -7,15 +7,11 @@ zend_test.observer.execute_internal=1
-<!-- internal enter tmpfile() -->
<!-- internal enter NoDiscard::__construct() -->
-<!-- internal enter flock() -->
-<!-- internal enter fclose() -->
+<!-- internal enter zend_test_nodiscard() -->
diff --git a/Zend/tests/attributes/nodiscard/010.phpt b/Zend/tests/attributes/nodiscard/010.phpt
new file mode 100644
index 0000000000000..5534fc3404da9
--- /dev/null
+++ b/Zend/tests/attributes/nodiscard/010.phpt
@@ -0,0 +1,12 @@
+--TEST--
+#[\NoDiscard]: Native function.
+--EXTENSIONS--
+--FILE--
+<?php
+?>
+--EXPECTF--
diff --git a/ext/opcache/tests/nodiscard_001.phpt b/ext/opcache/tests/nodiscard_001.phpt
index f4f7b8488e98a..7e232f8f44e41 100644
--- a/ext/opcache/tests/nodiscard_001.phpt
+++ b/ext/opcache/tests/nodiscard_001.phpt
@@ -7,14 +7,13 @@ opcache.optimization_level=-1
opcache.opt_debug_level=0x20000
--EXTENSIONS--
opcache
-(void)flock($f, LOCK_SH | LOCK_NB);
-$success = flock($f, LOCK_SH | LOCK_NB);
+(void)zend_test_nodiscard();
+$success = zend_test_nodiscard();
#[\NoDiscard]
function test() {
@@ -28,38 +27,26 @@ $obj = test();
$_main:
- ; (lines=29, args=0, vars=3, tmps=%d)
+ ; (lines=17, args=0, vars=2, tmps=%d)
; (after optimizer)
; %s
-0000 INIT_FCALL 0 %d string("tmpfile")
-0001 V3 = DO_ICALL
-0002 ASSIGN CV0($f) V3
-0003 INIT_FCALL 2 %d string("flock")
-0005 SEND_VAL int(5) 2
-0006 DO_FCALL_BY_NAME
-0007 INIT_FCALL 2 %d string("flock")
-0008 SEND_VAR CV0($f) 1
-0009 SEND_VAL int(5) 2
-0010 V3 = DO_ICALL
-0012 INIT_FCALL 2 %d string("flock")
-0013 SEND_VAR CV0($f) 1
-0014 SEND_VAL int(5) 2
-0015 V3 = DO_ICALL
-0016 ASSIGN CV1($success) V3
-0017 INIT_FCALL 1 %d string("fclose")
-0018 SEND_VAR CV0($f) 1
-0019 DO_ICALL
-0020 INIT_FCALL 0 %d string("test")
-0021 DO_FCALL_BY_NAME
-0022 INIT_FCALL 0 %d string("test")
-0023 V3 = DO_UCALL
-0024 FREE V3
-0025 INIT_FCALL 0 %d string("test")
-0026 V3 = DO_UCALL
-0027 ASSIGN CV2($obj) V3
-0028 RETURN int(1)
+0000 INIT_FCALL 0 %d string("zend_test_nodiscard")
+0001 DO_FCALL_BY_NAME
+0002 INIT_FCALL 0 %d string("zend_test_nodiscard")
+0003 V2 = DO_ICALL
+0004 FREE V2
+0005 INIT_FCALL 0 %d string("zend_test_nodiscard")
+0006 V2 = DO_ICALL
+0007 ASSIGN CV0($success) V2
+0008 INIT_FCALL 0 %d string("test")
+0009 DO_FCALL_BY_NAME
+0010 INIT_FCALL 0 %d string("test")
+0011 V2 = DO_UCALL
+0012 FREE V2
+0013 INIT_FCALL 0 %d string("test")
+0014 V2 = DO_UCALL
+0015 ASSIGN CV1($obj) V2
+0016 RETURN int(1)
test:
; (lines=3, args=0, vars=0, tmps=%d)
@@ -71,6 +58,6 @@ test:
LIVE RANGES:
0: 0001 - 0002 (new)
Warning: The return value of function test() should either be used or intentionally ignored by casting it as (void) in %s on line %d
diff --git a/ext/standard/basic_functions.stub.php b/ext/standard/basic_functions.stub.php
index b6533d8dc20e8..e7f4ff8844714 100644
--- a/ext/standard/basic_functions.stub.php
+++ b/ext/standard/basic_functions.stub.php
@@ -2732,7 +2732,6 @@ function proc_nice(int $priority): bool {}
* @param resource $stream
* @param int $would_block
*/
-#[\NoDiscard(message: "as locking the stream might have failed")]
function flock($stream, int $operation, &$would_block = null): bool {}
/**
diff --git a/ext/standard/basic_functions_arginfo.h b/ext/standard/basic_functions_arginfo.h
index d35377c900735..3d92288643159 100644
--- a/ext/standard/basic_functions_arginfo.h
+++ b/ext/standard/basic_functions_arginfo.h
- * Stub hash: 824ccb41163307bd0fad452b705a8222b6f42d09 */
+ * Stub hash: 85677dc3476d25b7820fd3a26fe39f2e9378b6e7 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_set_time_limit, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, seconds, IS_LONG, 0)
@@ -3205,7 +3205,7 @@ static const zend_function_entry ext_functions[] = {
#if defined(HAVE_NICE)
ZEND_FE(proc_nice, arginfo_proc_nice)
- ZEND_RAW_FENTRY("flock", zif_flock, arginfo_flock, ZEND_ACC_NODISCARD, NULL, NULL)
+ ZEND_FE(flock, arginfo_flock)
ZEND_FE(get_meta_tags, arginfo_get_meta_tags)
ZEND_FE(pclose, arginfo_pclose)
ZEND_FE(popen, arginfo_popen)
@@ -4039,15 +4039,6 @@ static void register_basic_functions_symbols(int module_number)
ZVAL_COPY_VALUE(&attribute_Deprecated_func_utf8_decode_0->args[1].value, &attribute_Deprecated_func_utf8_decode_0_arg1);
attribute_Deprecated_func_utf8_decode_0->args[1].name = ZSTR_KNOWN(ZEND_STR_MESSAGE);
- zend_string *attribute_name_NoDiscard_func_flock_0 = zend_string_init_interned("NoDiscard", sizeof("NoDiscard") - 1, 1);
- zend_attribute *attribute_NoDiscard_func_flock_0 = zend_add_function_attribute(zend_hash_str_find_ptr(CG(function_table), "flock", sizeof("flock") - 1), attribute_name_NoDiscard_func_flock_0, 1);
- zval attribute_NoDiscard_func_flock_0_arg0;
- zend_string *attribute_NoDiscard_func_flock_0_arg0_str = zend_string_init("as locking the stream might have failed", strlen("as locking the stream might have failed"), 1);
- ZVAL_STR(&attribute_NoDiscard_func_flock_0_arg0, attribute_NoDiscard_func_flock_0_arg0_str);
- ZVAL_COPY_VALUE(&attribute_NoDiscard_func_flock_0->args[0].value, &attribute_NoDiscard_func_flock_0_arg0);
- attribute_NoDiscard_func_flock_0->args[0].name = ZSTR_KNOWN(ZEND_STR_MESSAGE);
zend_add_parameter_attribute(zend_hash_str_find_ptr(CG(function_table), "password_hash", sizeof("password_hash") - 1), 0, ZSTR_KNOWN(ZEND_STR_SENSITIVEPARAMETER), 0);
zend_add_parameter_attribute(zend_hash_str_find_ptr(CG(function_table), "password_verify", sizeof("password_verify") - 1), 0, ZSTR_KNOWN(ZEND_STR_SENSITIVEPARAMETER), 0);
diff --git a/ext/zend_test/test.c b/ext/zend_test/test.c
index b9190f6753052..ba18639aead82 100644
--- a/ext/zend_test/test.c
+++ b/ext/zend_test/test.c
@@ -124,6 +124,13 @@ static ZEND_FUNCTION(zend_test_deprecated_attr)
}
+static ZEND_FUNCTION(zend_test_nodiscard)
+{
+ ZEND_PARSE_PARAMETERS_NONE();
+ RETURN_LONG(1);
static ZEND_FUNCTION(zend_test_deprecated_nodiscard)
{
diff --git a/ext/zend_test/test.stub.php b/ext/zend_test/test.stub.php
index 921dadd00ce15..10272c51cad49 100644
--- a/ext/zend_test/test.stub.php
+++ b/ext/zend_test/test.stub.php
@@ -218,6 +218,8 @@ function zend_test_deprecated(mixed $arg = null): void {}
function zend_test_deprecated_attr(): void {}
+ #[\NoDiscard(message: "custom message")]
+ function zend_test_nodiscard(): int {}
#[\NoDiscard(message: "custom message 2")]
diff --git a/ext/zend_test/test_arginfo.h b/ext/zend_test/test_arginfo.h
index 391f2fc500b02..62b57223dac2a 100644
--- a/ext/zend_test/test_arginfo.h
+++ b/ext/zend_test/test_arginfo.h
- * Stub hash: eebe535d0295f707201ff751e38a5ad3837dbbd2 */
+ * Stub hash: bedc3883fbfe2491c95375beb13140e7fcfd83a5 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_array_return, 0, 0, IS_ARRAY, 0)
@@ -22,9 +22,11 @@ ZEND_END_ARG_INFO()
#define arginfo_zend_test_deprecated_attr arginfo_zend_test_void_return
-ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_deprecated_nodiscard, 0, 0, IS_LONG, 0)
+#define arginfo_zend_test_deprecated_nodiscard arginfo_zend_test_nodiscard
#define arginfo_zend_test_aliased arginfo_zend_test_void_return
#define arginfo_zend_test_deprecated_aliased arginfo_zend_test_void_return
@@ -131,7 +133,7 @@ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_is_string_marked_as_va
ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0)
-#define arginfo_zend_get_map_ptr_last arginfo_zend_test_deprecated_nodiscard
+#define arginfo_zend_get_map_ptr_last arginfo_zend_test_nodiscard
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_crash, 0, 0, IS_VOID, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, message, IS_STRING, 1, "null")
@@ -189,7 +191,7 @@ ZEND_END_ARG_INFO()
#define arginfo_ZendTestNS2_ZendSubNS_namespaced_deprecated_aliased_func arginfo_zend_test_void_return
-#define arginfo_class__ZendTestClass_is_object arginfo_zend_test_deprecated_nodiscard
+#define arginfo_class__ZendTestClass_is_object arginfo_zend_test_nodiscard
#define arginfo_class__ZendTestClass___toString arginfo_zend_get_current_func_name
@@ -264,6 +266,7 @@ static ZEND_FUNCTION(zend_test_void_return);
static ZEND_FUNCTION(zend_test_compile_string);
static ZEND_FUNCTION(zend_test_deprecated);
static ZEND_FUNCTION(zend_test_deprecated_attr);
+static ZEND_FUNCTION(zend_test_nodiscard);
static ZEND_FUNCTION(zend_test_deprecated_nodiscard);
static ZEND_FUNCTION(zend_create_unterminated_string);
static ZEND_FUNCTION(zend_terminate_string);
@@ -361,6 +364,11 @@ static const zend_function_entry ext_functions[] = {
ZEND_RAW_FENTRY("zend_test_deprecated_attr", zif_zend_test_deprecated_attr, arginfo_zend_test_deprecated_attr, ZEND_ACC_DEPRECATED)
+#if (PHP_VERSION_ID >= 80400)
+ ZEND_RAW_FENTRY("zend_test_nodiscard", zif_zend_test_nodiscard, arginfo_zend_test_nodiscard, ZEND_ACC_NODISCARD, NULL, NULL)
+ ZEND_RAW_FENTRY("zend_test_nodiscard", zif_zend_test_nodiscard, arginfo_zend_test_nodiscard, ZEND_ACC_NODISCARD)
+#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("zend_test_deprecated_nodiscard", zif_zend_test_deprecated_nodiscard, arginfo_zend_test_deprecated_nodiscard, ZEND_ACC_DEPRECATED|ZEND_ACC_NODISCARD, NULL, NULL)
@@ -572,6 +580,15 @@ static void register_test_symbols(int module_number)
ZVAL_COPY_VALUE(&attribute_Deprecated_func_zend_test_deprecated_attr_0->args[0].value, &attribute_Deprecated_func_zend_test_deprecated_attr_0_arg0);
attribute_Deprecated_func_zend_test_deprecated_attr_0->args[0].name = ZSTR_KNOWN(ZEND_STR_MESSAGE);
+ zend_attribute *attribute_NoDiscard_func_zend_test_nodiscard_0 = zend_add_function_attribute(zend_hash_str_find_ptr(CG(function_table), "zend_test_nodiscard", sizeof("zend_test_nodiscard") - 1), attribute_name_NoDiscard_func_zend_test_nodiscard_0, 1);
+ zend_string_release(attribute_name_NoDiscard_func_zend_test_nodiscard_0);
+ zval attribute_NoDiscard_func_zend_test_nodiscard_0_arg0;
+ zend_string *attribute_NoDiscard_func_zend_test_nodiscard_0_arg0_str = zend_string_init("custom message", strlen("custom message"), 1);
+ ZVAL_COPY_VALUE(&attribute_NoDiscard_func_zend_test_nodiscard_0->args[0].value, &attribute_NoDiscard_func_zend_test_nodiscard_0_arg0);
+ attribute_NoDiscard_func_zend_test_nodiscard_0->args[0].name = ZSTR_KNOWN(ZEND_STR_MESSAGE);
zend_string *attribute_name_Deprecated_func_zend_test_deprecated_nodiscard_0 = zend_string_init_interned("Deprecated", sizeof("Deprecated") - 1, 1);
zend_attribute *attribute_Deprecated_func_zend_test_deprecated_nodiscard_0 = zend_add_function_attribute(zend_hash_str_find_ptr(CG(function_table), "zend_test_deprecated_nodiscard", sizeof("zend_test_deprecated_nodiscard") - 1), attribute_name_Deprecated_func_zend_test_deprecated_nodiscard_0, 1);
zend_string_release(attribute_name_Deprecated_func_zend_test_deprecated_nodiscard_0); | [
"-0004 SEND_VAR CV0($f) 1",
"-0011 FREE V3",
"-\tzend_string_release(attribute_name_NoDiscard_func_flock_0);",
"+}",
"+ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_nodiscard, 0, 0, IS_LONG, 0)",
"+#else",
"+\tzend_string *attribute_name_NoDiscard_func_zend_test_nodiscard_0 = zend_string_init_interned(\"NoDiscard\", sizeof(\"NoDiscard\") - 1, 1);",
"+\tZVAL_STR(&attribute_NoDiscard_func_zend_test_nodiscard_0_arg0, attribute_NoDiscard_func_zend_test_nodiscard_0_arg0_str);"
] | [
99,
106,
190,
213,
247,
287,
297,
302
] | {
"additions": 71,
"author": "TimWolla",
"deletions": 66,
"html_url": "https://github.com/php/php-src/pull/18255",
"issue_id": 18255,
"merged_at": "2025-04-08T12:23:03Z",
"omission_probability": 0.1,
"pr_number": 18255,
"repo": "php/php-src",
"title": "ext/standard: Remove `#[\\NoDiscard]` from `flock()`",
"total_changes": 137
} |
764 | diff --git a/Zend/zend_inheritance.c b/Zend/zend_inheritance.c
index 8747e11d151f..53cd8533fd3e 100644
--- a/Zend/zend_inheritance.c
+++ b/Zend/zend_inheritance.c
@@ -96,7 +96,7 @@ static void zend_type_copy_ctor(zend_type *const type, bool use_arena, bool pers
}
}
-static zend_function *zend_duplicate_internal_function(zend_function *func, const zend_class_entry *ce) /* {{{ */
+static zend_function *zend_duplicate_internal_function(const zend_function *func, const zend_class_entry *ce) /* {{{ */
{
zend_function *new_function;
@@ -310,7 +310,7 @@ static zend_class_entry *lookup_class(zend_class_entry *scope, zend_string *name
}
/* Instanceof that's safe to use on unlinked classes. */
-static bool unlinked_instanceof(zend_class_entry *ce1, const zend_class_entry *ce2) {
+static bool unlinked_instanceof(const zend_class_entry *ce1, const zend_class_entry *ce2) {
if (ce1 == ce2) {
return 1;
}
@@ -347,7 +347,7 @@ static bool unlinked_instanceof(zend_class_entry *ce1, const zend_class_entry *c
}
} else {
for (i = 0; i < ce1->num_interfaces; i++) {
- zend_class_entry *ce = zend_lookup_class_ex(
+ const zend_class_entry *ce = zend_lookup_class_ex(
ce1->interface_names[i].name, ce1->interface_names[i].lc_name,
ZEND_FETCH_CLASS_ALLOW_UNLINKED | ZEND_FETCH_CLASS_NO_AUTOLOAD);
/* Avoid recursing if class implements itself. */
@@ -362,7 +362,7 @@ static bool unlinked_instanceof(zend_class_entry *ce1, const zend_class_entry *c
}
static bool zend_type_permits_self(
- zend_type type, zend_class_entry *scope, zend_class_entry *self) {
+ zend_type type, const zend_class_entry *scope, zend_class_entry *self) {
if (ZEND_TYPE_FULL_MASK(type) & MAY_BE_OBJECT) {
return 1;
}
@@ -374,7 +374,7 @@ static bool zend_type_permits_self(
ZEND_TYPE_FOREACH(type, single_type) {
if (ZEND_TYPE_HAS_NAME(*single_type)) {
zend_string *name = resolve_class_name(scope, ZEND_TYPE_NAME(*single_type));
- zend_class_entry *ce = lookup_class(self, name);
+ const zend_class_entry *ce = lookup_class(self, name);
if (ce && unlinked_instanceof(self, ce)) {
return 1;
}
@@ -584,7 +584,7 @@ static inheritance_status zend_is_class_subtype_of_type(
return is_intersection ? INHERITANCE_SUCCESS : INHERITANCE_ERROR;
}
-static zend_string *get_class_from_type(zend_class_entry *scope, zend_type single_type) {
+static zend_string *get_class_from_type(const zend_class_entry *scope, zend_type single_type) {
if (ZEND_TYPE_HAS_NAME(single_type)) {
return resolve_class_name(scope, ZEND_TYPE_NAME(single_type));
}
@@ -706,7 +706,6 @@ ZEND_API inheritance_status zend_perform_covariant_type_check(
}
}
- zend_type *single_type;
inheritance_status early_exit_status;
bool have_unresolved = false;
@@ -728,6 +727,7 @@ ZEND_API inheritance_status zend_perform_covariant_type_check(
* We need to iterate over fe_type (U_i) first and the logic is independent of
* whether proto_type is a union or intersection (only the inner check differs). */
early_exit_status = INHERITANCE_ERROR;
+ zend_type *single_type;
ZEND_TYPE_FOREACH(fe_type, single_type) {
inheritance_status status;
/* Union has an intersection type as it's member */
@@ -790,7 +790,7 @@ static inheritance_status zend_do_perform_implementation_check(
const zend_function *fe, zend_class_entry *fe_scope,
const zend_function *proto, zend_class_entry *proto_scope) /* {{{ */
{
- uint32_t i, num_args, proto_num_args, fe_num_args;
+ uint32_t num_args, proto_num_args, fe_num_args;
inheritance_status status, local_status;
bool proto_is_variadic, fe_is_variadic;
@@ -831,7 +831,7 @@ static inheritance_status zend_do_perform_implementation_check(
num_args = MAX(proto_num_args, fe_num_args);
status = INHERITANCE_SUCCESS;
- for (i = 0; i < num_args; i++) {
+ for (uint32_t i = 0; i < num_args; i++) {
zend_arg_info *proto_arg_info =
i < proto_num_args ? &proto->common.arg_info[i] :
proto_is_variadic ? &proto->common.arg_info[proto_num_args - 1] : NULL;
@@ -933,7 +933,7 @@ static ZEND_COLD zend_string *zend_get_function_declaration(
smart_str_appendc(&str, '(');
if (fptr->common.arg_info) {
- uint32_t i, num_args, required;
+ uint32_t num_args, required;
zend_arg_info *arg_info = fptr->common.arg_info;
required = fptr->common.required_num_args;
@@ -941,7 +941,7 @@ static ZEND_COLD zend_string *zend_get_function_declaration(
if (fptr->common.fn_flags & ZEND_ACC_VARIADIC) {
num_args++;
}
- for (i = 0; i < num_args;) {
+ for (uint32_t i = 0; i < num_args;) {
zend_append_type_hint(&str, scope, arg_info, 0);
if (ZEND_ARG_SEND_MODE(arg_info)) {
@@ -973,7 +973,7 @@ static ZEND_COLD zend_string *zend_get_function_declaration(
{
uint32_t idx = i;
zend_op *op = fptr->op_array.opcodes;
- zend_op *end = op + fptr->op_array.last;
+ const zend_op *end = op + fptr->op_array.last;
++idx;
while (op < end) {
@@ -1366,7 +1366,7 @@ static inheritance_status verify_property_type_compatibility(
return INHERITANCE_SUCCESS;
}
-static bool property_has_operation(zend_property_info *prop_info, zend_property_hook_kind kind)
+static bool property_has_operation(const zend_property_info *prop_info, zend_property_hook_kind kind)
{
return (!(prop_info->flags & ZEND_ACC_VIRTUAL)
&& (kind == ZEND_PROPERTY_HOOK_GET || !(prop_info->flags & ZEND_ACC_READONLY)))
@@ -1451,10 +1451,9 @@ static prop_variance prop_get_variance(const zend_property_info *prop_info) {
static void do_inherit_property(zend_property_info *parent_info, zend_string *key, zend_class_entry *ce) /* {{{ */
{
zval *child = zend_hash_find_known_hash(&ce->properties_info, key);
- zend_property_info *child_info;
if (UNEXPECTED(child)) {
- child_info = Z_PTR_P(child);
+ zend_property_info *child_info = Z_PTR_P(child);
if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_CHANGED)) {
child_info->flags |= ZEND_ACC_CHANGED;
}
@@ -1596,7 +1595,6 @@ static void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_en
{
/* expects interface to be contained in ce's interface list already */
uint32_t i, ce_num, if_num = iface->num_interfaces;
- zend_class_entry *entry;
ce_num = ce->num_interfaces;
@@ -1608,7 +1606,7 @@ static void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_en
/* Inherit the interfaces, only if they're not already inherited by the class */
while (if_num--) {
- entry = iface->interfaces[if_num];
+ zend_class_entry *entry = iface->interfaces[if_num];
for (i = 0; i < ce_num; i++) {
if (ce->interfaces[i] == entry) {
break;
@@ -1651,7 +1649,7 @@ static inheritance_status class_constant_types_compatible(const zend_class_const
}
static bool do_inherit_constant_check(
- zend_class_entry *ce, zend_class_constant *parent_constant, zend_string *name);
+ zend_class_entry *ce, const zend_class_constant *parent_constant, zend_string *name);
static void do_inherit_class_constant(zend_string *name, zend_class_constant *parent_const, zend_class_entry *ce) /* {{{ */
{
@@ -1724,7 +1722,7 @@ void zend_build_properties_info_table(zend_class_entry *ce)
} ZEND_HASH_FOREACH_END();
}
-ZEND_API void zend_verify_hooked_property(zend_class_entry *ce, zend_property_info *prop_info, zend_string *prop_name)
+ZEND_API void zend_verify_hooked_property(const zend_class_entry *ce, zend_property_info *prop_info, zend_string *prop_name)
{
if (!prop_info->hooks) {
return;
@@ -1748,7 +1746,7 @@ ZEND_API void zend_verify_hooked_property(zend_class_entry *ce, zend_property_in
ZVAL_NULL(&ce->default_properties_table[OBJ_PROP_TO_NUM(prop_info->offset)]);
}
for (uint32_t i = 0; i < ZEND_PROPERTY_HOOK_COUNT; i++) {
- zend_function *func = prop_info->hooks[i];
+ const zend_function *func = prop_info->hooks[i];
if (func) {
if ((zend_property_hook_kind)i == ZEND_PROPERTY_HOOK_GET
&& (func->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE)
@@ -1830,7 +1828,6 @@ static void zend_link_hooked_object_iter(zend_class_entry *ce) {
ZEND_API void zend_do_inheritance_ex(zend_class_entry *ce, zend_class_entry *parent_ce, bool checked) /* {{{ */
{
zend_property_info *property_info;
- zend_function *func;
zend_string *key;
if (UNEXPECTED(ce->ce_flags & ZEND_ACC_INTERFACE)) {
@@ -2021,6 +2018,7 @@ ZEND_API void zend_do_inheritance_ex(zend_class_entry *ce, zend_class_entry *par
if (!checked) {
flags |= ZEND_INHERITANCE_CHECK_PROTO | ZEND_INHERITANCE_CHECK_VISIBILITY;
}
+ zend_function *func;
ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&parent_ce->function_table, key, func) {
do_inherit_method(key, func, ce, 0, flags);
} ZEND_HASH_FOREACH_END();
@@ -2079,7 +2077,7 @@ static zend_always_inline bool check_trait_property_or_constant_value_compatibil
/** @return bool Returns true if the class constant should be inherited, i.e. whether it doesn't already exist. */
static bool do_inherit_constant_check(
- zend_class_entry *ce, zend_class_constant *parent_constant, zend_string *name
+ zend_class_entry *ce, const zend_class_constant *parent_constant, zend_string *name
) {
zval *zv = zend_hash_find_known_hash(&ce->constants_table, name);
if (zv == NULL) {
@@ -2126,7 +2124,7 @@ static bool do_inherit_constant_check(
}
/* }}} */
-static void do_inherit_iface_constant(zend_string *name, zend_class_constant *c, zend_class_entry *ce, zend_class_entry *iface) /* {{{ */
+static void do_inherit_iface_constant(zend_string *name, zend_class_constant *c, zend_class_entry *ce, const zend_class_entry *iface) /* {{{ */
{
if (do_inherit_constant_check(ce, c, name)) {
zend_class_constant *ct;
@@ -2196,27 +2194,27 @@ static void do_interface_implementation(zend_class_entry *ce, zend_class_entry *
ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface) /* {{{ */
{
- uint32_t i, ignore = 0;
+ bool ignore = false;
uint32_t current_iface_num = ce->num_interfaces;
uint32_t parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0;
- zend_string *key;
- zend_class_constant *c;
ZEND_ASSERT(ce->ce_flags & ZEND_ACC_LINKED);
- for (i = 0; i < ce->num_interfaces; i++) {
+ for (uint32_t i = 0; i < ce->num_interfaces; i++) {
if (ce->interfaces[i] == NULL) {
memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i));
i--;
} else if (ce->interfaces[i] == iface) {
if (EXPECTED(i < parent_iface_num)) {
- ignore = 1;
+ ignore = true;
} else {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name));
}
}
}
if (ignore) {
+ zend_string *key;
+ zend_class_constant *c;
/* Check for attempt to redeclare interface constants */
ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&iface->constants_table, key, c) {
do_inherit_constant_check(ce, c, key);
@@ -2238,15 +2236,14 @@ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry
static void zend_do_implement_interfaces(zend_class_entry *ce, zend_class_entry **interfaces) /* {{{ */
{
- zend_class_entry *iface;
uint32_t num_parent_interfaces = ce->parent ? ce->parent->num_interfaces : 0;
uint32_t num_interfaces = num_parent_interfaces;
zend_string *key;
zend_class_constant *c;
- uint32_t i, j;
+ uint32_t i;
for (i = 0; i < ce->num_interfaces; i++) {
- iface = interfaces[num_parent_interfaces + i];
+ zend_class_entry *iface = interfaces[num_parent_interfaces + i];
if (!(iface->ce_flags & ZEND_ACC_LINKED)) {
add_dependency_obligation(ce, iface);
}
@@ -2255,7 +2252,7 @@ static void zend_do_implement_interfaces(zend_class_entry *ce, zend_class_entry
zend_error_noreturn(E_ERROR, "%s cannot implement %s - it is not an interface", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name));
return;
}
- for (j = 0; j < num_interfaces; j++) {
+ for (uint32_t j = 0; j < num_interfaces; j++) {
if (interfaces[j] == iface) {
if (j >= num_parent_interfaces) {
efree(interfaces);
@@ -2304,7 +2301,7 @@ static void zend_do_implement_interfaces(zend_class_entry *ce, zend_class_entry
/* }}} */
-void zend_inheritance_check_override(zend_class_entry *ce)
+void zend_inheritance_check_override(const zend_class_entry *ce)
{
zend_function *f;
@@ -2426,7 +2423,7 @@ static void zend_fixup_trait_method(zend_function *fn, zend_class_entry *ce) /*
}
/* }}} */
-static void zend_traits_check_private_final_inheritance(uint32_t original_fn_flags, zend_function *fn_copy, zend_string *name)
+static void zend_traits_check_private_final_inheritance(uint32_t original_fn_flags, const zend_function *fn_copy, const zend_string *name)
{
/* If the function was originally already private+final, then it will have
* already been warned about. Only emit this error when the used trait method
@@ -2442,7 +2439,6 @@ static void zend_traits_check_private_final_inheritance(uint32_t original_fn_fla
static void zend_traits_copy_functions(zend_string *fnname, zend_function *fn, zend_class_entry *ce, HashTable *exclude_table, zend_class_entry **aliases) /* {{{ */
{
zend_trait_alias *alias, **alias_ptr;
- zend_string *lcname;
zend_function fn_copy;
int i;
@@ -2466,7 +2462,7 @@ static void zend_traits_copy_functions(zend_string *fnname, zend_function *fn, z
zend_traits_check_private_final_inheritance(fn->common.fn_flags, &fn_copy, alias->alias);
- lcname = zend_string_tolower(alias->alias);
+ zend_string *lcname = zend_string_tolower(alias->alias);
zend_add_trait_method(ce, alias->alias, lcname, &fn_copy);
zend_string_release_ex(lcname, 0);
}
@@ -2510,16 +2506,14 @@ static void zend_traits_copy_functions(zend_string *fnname, zend_function *fn, z
}
/* }}} */
-static uint32_t zend_check_trait_usage(zend_class_entry *ce, zend_class_entry *trait, zend_class_entry **traits) /* {{{ */
+static uint32_t zend_check_trait_usage(const zend_class_entry *ce, const zend_class_entry *trait, zend_class_entry **traits) /* {{{ */
{
- uint32_t i;
-
if (UNEXPECTED((trait->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT)) {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s is not a trait, Only traits may be used in 'as' and 'insteadof' statements", ZSTR_VAL(trait->name));
return 0;
}
- for (i = 0; i < ce->num_traits; i++) {
+ for (uint32_t i = 0; i < ce->num_traits; i++) {
if (traits[i] == trait) {
return i;
}
@@ -2532,7 +2526,6 @@ static uint32_t zend_check_trait_usage(zend_class_entry *ce, zend_class_entry *t
static void zend_traits_init_trait_structures(zend_class_entry *ce, zend_class_entry **traits, HashTable ***exclude_tables_ptr, zend_class_entry ***aliases_ptr) /* {{{ */
{
size_t i, j = 0;
- zend_trait_precedence **precedences;
zend_trait_precedence *cur_precedence;
zend_trait_method_reference *cur_method_ref;
zend_string *lc_trait_name;
@@ -2545,7 +2538,7 @@ static void zend_traits_init_trait_structures(zend_class_entry *ce, zend_class_e
if (ce->trait_precedences) {
exclude_tables = ecalloc(ce->num_traits, sizeof(HashTable*));
i = 0;
- precedences = ce->trait_precedences;
+ zend_trait_precedence **precedences = ce->trait_precedences;
ce->trait_precedences = NULL;
while ((cur_precedence = precedences[i])) {
/** Resolve classes for all precedence operations. */
@@ -2619,7 +2612,7 @@ static void zend_traits_init_trait_structures(zend_class_entry *ce, zend_class_e
aliases = ecalloc(i, sizeof(zend_class_entry*));
i = 0;
while (ce->trait_aliases[i]) {
- zend_trait_alias *cur_alias = ce->trait_aliases[i];
+ const zend_trait_alias *cur_alias = ce->trait_aliases[i];
cur_method_ref = &ce->trait_aliases[i]->trait_method;
lcname = zend_string_tolower(cur_method_ref->method_name);
if (cur_method_ref->class_name) {
@@ -2736,10 +2729,8 @@ static const zend_class_entry* find_first_constant_definition(const zend_class_e
* process like this is needed to find the location of the first definition
* of the constant from traits.
*/
- size_t i;
-
if (colliding_ce == ce) {
- for (i = 0; i < current_trait; i++) {
+ for (size_t i = 0; i < current_trait; i++) {
if (traits[i]
&& zend_hash_exists(&traits[i]->constants_table, constant_name)) {
return traits[i];
@@ -2806,9 +2797,7 @@ static bool do_trait_constant_check(
static void zend_do_traits_constant_binding(zend_class_entry *ce, zend_class_entry **traits) /* {{{ */
{
- size_t i;
-
- for (i = 0; i < ce->num_traits; i++) {
+ for (uint32_t i = 0; i < ce->num_traits; i++) {
zend_string *constant_name;
zend_class_constant *constant;
@@ -2850,10 +2839,8 @@ static void zend_do_traits_constant_binding(zend_class_entry *ce, zend_class_ent
static const zend_class_entry* find_first_property_definition(const zend_class_entry *ce, zend_class_entry **traits, size_t current_trait, zend_string *prop_name, const zend_class_entry *colliding_ce) /* {{{ */
{
- size_t i;
-
if (colliding_ce == ce) {
- for (i = 0; i < current_trait; i++) {
+ for (size_t i = 0; i < current_trait; i++) {
if (traits[i]
&& zend_hash_exists(&traits[i]->properties_info, prop_name)) {
return traits[i];
@@ -2867,20 +2854,17 @@ static const zend_class_entry* find_first_property_definition(const zend_class_e
static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_entry **traits) /* {{{ */
{
- size_t i;
zend_property_info *property_info;
const zend_property_info *colliding_prop;
- zend_property_info *new_prop;
zend_string* prop_name;
zval* prop_value;
- zend_string *doc_comment;
/* In the following steps the properties are inserted into the property table
* for that, a very strict approach is applied:
* - check for compatibility, if not compatible with any property in class -> fatal
* - if compatible, then strict notice
*/
- for (i = 0; i < ce->num_traits; i++) {
+ for (uint32_t i = 0; i < ce->num_traits; i++) {
if (!traits[i]) {
continue;
}
@@ -2960,12 +2944,13 @@ static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_ent
prop_value = &tmp_prop_value;
ZVAL_UNDEF(&tmp_prop_value);
}
- doc_comment = property_info->doc_comment ? zend_string_copy(property_info->doc_comment) : NULL;
+
+ zend_string *doc_comment = property_info->doc_comment ? zend_string_copy(property_info->doc_comment) : NULL;
zend_type type = property_info->type;
/* Assumption: only userland classes can use traits, as such the type must be arena allocated */
zend_type_copy_ctor(&type, /* use arena */ true, /* persistent */ false);
- new_prop = zend_declare_typed_property(ce, prop_name, prop_value, flags, doc_comment, type);
+ zend_property_info *new_prop = zend_declare_typed_property(ce, prop_name, prop_value, flags, doc_comment, type);
if (property_info->attributes) {
new_prop->attributes = property_info->attributes;
@@ -2978,9 +2963,9 @@ static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_ent
zend_function **hooks = new_prop->hooks =
zend_arena_alloc(&CG(arena), ZEND_PROPERTY_HOOK_STRUCT_SIZE);
memcpy(hooks, property_info->hooks, ZEND_PROPERTY_HOOK_STRUCT_SIZE);
- for (uint32_t i = 0; i < ZEND_PROPERTY_HOOK_COUNT; i++) {
- if (hooks[i]) {
- zend_function *old_fn = hooks[i];
+ for (uint32_t j = 0; j < ZEND_PROPERTY_HOOK_COUNT; j++) {
+ if (hooks[j]) {
+ zend_function *old_fn = hooks[j];
/* Hooks are not yet supported for internal properties. */
ZEND_ASSERT(ZEND_USER_CODE(old_fn->type));
@@ -2995,7 +2980,7 @@ static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_ent
zend_fixup_trait_method(new_fn, ce);
- hooks[i] = new_fn;
+ hooks[j] = new_fn;
}
}
ce->ce_flags |= ZEND_ACC_USE_GUARDS;
@@ -3221,7 +3206,7 @@ static void add_property_hook_obligation(
static void resolve_delayed_variance_obligations(zend_class_entry *ce);
-static void check_variance_obligation(variance_obligation *obligation) {
+static void check_variance_obligation(const variance_obligation *obligation) {
if (obligation->type == OBLIGATION_DEPENDENCY) {
zend_class_entry *dependency_ce = obligation->dependency_ce;
if (dependency_ce->ce_flags & ZEND_ACC_UNRESOLVED_VARIANCE) {
@@ -3260,7 +3245,7 @@ static void check_variance_obligation(variance_obligation *obligation) {
}
}
-static void load_delayed_classes(zend_class_entry *ce) {
+static void load_delayed_classes(const zend_class_entry *ce) {
HashTable *delayed_autoloads = CG(delayed_autoloads);
if (!delayed_autoloads) {
return;
@@ -3289,11 +3274,11 @@ static void load_delayed_classes(zend_class_entry *ce) {
}
static void resolve_delayed_variance_obligations(zend_class_entry *ce) {
- HashTable *all_obligations = CG(delayed_variance_obligations), *obligations;
+ HashTable *all_obligations = CG(delayed_variance_obligations);
zend_ulong num_key = (zend_ulong) (uintptr_t) ce;
ZEND_ASSERT(all_obligations != NULL);
- obligations = zend_hash_index_find_ptr(all_obligations, num_key);
+ const HashTable *obligations = zend_hash_index_find_ptr(all_obligations, num_key);
ZEND_ASSERT(obligations != NULL);
variance_obligation *obligation;
@@ -3327,7 +3312,7 @@ static void check_unrecoverable_load_failure(const zend_class_entry *ce) {
} while (0)
static zend_op_array *zend_lazy_method_load(
- zend_op_array *op_array, zend_class_entry *ce, const zend_class_entry *pce) {
+ const zend_op_array *op_array, zend_class_entry *ce, const zend_class_entry *pce) {
ZEND_ASSERT(op_array->type == ZEND_USER_FUNCTION);
ZEND_ASSERT(op_array->scope == pce);
ZEND_ASSERT(op_array->prototype == NULL);
@@ -3341,12 +3326,10 @@ static zend_op_array *zend_lazy_method_load(
return new_op_array;
}
-static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
+static zend_class_entry *zend_lazy_class_load(const zend_class_entry *pce)
{
- zend_class_entry *ce;
- Bucket *p, *end;
+ zend_class_entry *ce = zend_arena_alloc(&CG(arena), sizeof(zend_class_entry));
- ce = zend_arena_alloc(&CG(arena), sizeof(zend_class_entry));
memcpy(ce, pce, sizeof(zend_class_entry));
ce->ce_flags &= ~ZEND_ACC_IMMUTABLE;
ce->refcount = 1;
@@ -3361,7 +3344,7 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
if (ce->default_properties_table) {
zval *dst = emalloc(sizeof(zval) * ce->default_properties_count);
zval *src = ce->default_properties_table;
- zval *end = src + ce->default_properties_count;
+ const zval *end = src + ce->default_properties_count;
ce->default_properties_table = dst;
for (; src != end; src++, dst++) {
@@ -3372,11 +3355,11 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
/* methods */
ce->function_table.pDestructor = ZEND_FUNCTION_DTOR;
if (!(HT_FLAGS(&ce->function_table) & HASH_FLAG_UNINITIALIZED)) {
- p = emalloc(HT_SIZE(&ce->function_table));
+ Bucket *p = emalloc(HT_SIZE(&ce->function_table));
memcpy(p, HT_GET_DATA_ADDR(&ce->function_table), HT_USED_SIZE(&ce->function_table));
HT_SET_DATA_ADDR(&ce->function_table, p);
p = ce->function_table.arData;
- end = p + ce->function_table.nNumUsed;
+ const Bucket *end = p + ce->function_table.nNumUsed;
for (; p != end; p++) {
zend_op_array *op_array = Z_PTR(p->val);
zend_op_array *new_op_array = Z_PTR(p->val) = zend_lazy_method_load(op_array, ce, pce);
@@ -3401,7 +3384,7 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
if (ce->default_static_members_table) {
zval *dst = emalloc(sizeof(zval) * ce->default_static_members_count);
zval *src = ce->default_static_members_table;
- zval *end = src + ce->default_static_members_count;
+ const zval *end = src + ce->default_static_members_count;
ce->default_static_members_table = dst;
for (; src != end; src++, dst++) {
@@ -3412,15 +3395,15 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
/* properties_info */
if (!(HT_FLAGS(&ce->properties_info) & HASH_FLAG_UNINITIALIZED)) {
- p = emalloc(HT_SIZE(&ce->properties_info));
+ Bucket *p = emalloc(HT_SIZE(&ce->properties_info));
memcpy(p, HT_GET_DATA_ADDR(&ce->properties_info), HT_USED_SIZE(&ce->properties_info));
HT_SET_DATA_ADDR(&ce->properties_info, p);
p = ce->properties_info.arData;
- end = p + ce->properties_info.nNumUsed;
+ const Bucket *end = p + ce->properties_info.nNumUsed;
for (; p != end; p++) {
- zend_property_info *prop_info, *new_prop_info;
+ zend_property_info *new_prop_info;
- prop_info = Z_PTR(p->val);
+ const zend_property_info *prop_info = Z_PTR(p->val);
ZEND_ASSERT(prop_info->ce == pce);
ZEND_ASSERT(prop_info->prototype == prop_info);
new_prop_info= zend_arena_alloc(&CG(arena), sizeof(zend_property_info));
@@ -3448,15 +3431,15 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
/* constants table */
if (!(HT_FLAGS(&ce->constants_table) & HASH_FLAG_UNINITIALIZED)) {
- p = emalloc(HT_SIZE(&ce->constants_table));
+ Bucket *p = emalloc(HT_SIZE(&ce->constants_table));
memcpy(p, HT_GET_DATA_ADDR(&ce->constants_table), HT_USED_SIZE(&ce->constants_table));
HT_SET_DATA_ADDR(&ce->constants_table, p);
p = ce->constants_table.arData;
- end = p + ce->constants_table.nNumUsed;
+ const Bucket *end = p + ce->constants_table.nNumUsed;
for (; p != end; p++) {
- zend_class_constant *c, *new_c;
+ zend_class_constant *new_c;
- c = Z_PTR(p->val);
+ const zend_class_constant *c = Z_PTR(p->val);
ZEND_ASSERT(c->ce == pce);
new_c = zend_arena_alloc(&CG(arena), sizeof(zend_class_constant));
Z_PTR(p->val) = new_c;
@@ -3481,7 +3464,7 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
} while (0)
#endif
-ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, zend_string *key) /* {{{ */
+ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, const zend_string *key) /* {{{ */
{
/* Load parent/interface dependencies first, so we can still gracefully abort linking
* with an exception and remove the class from the class table. This is only possible
@@ -3784,7 +3767,7 @@ ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string
/* }}} */
/* Check whether early binding is prevented due to unresolved types in inheritance checks. */
-static inheritance_status zend_can_early_bind(zend_class_entry *ce, zend_class_entry *parent_ce) /* {{{ */
+static inheritance_status zend_can_early_bind(zend_class_entry *ce, const zend_class_entry *parent_ce) /* {{{ */
{
zend_string *key;
zend_function *parent_func;
diff --git a/Zend/zend_inheritance.h b/Zend/zend_inheritance.h
index 477874181e41..7171a9385f3b 100644
--- a/Zend/zend_inheritance.h
+++ b/Zend/zend_inheritance.h
@@ -32,13 +32,13 @@ static zend_always_inline void zend_do_inheritance(zend_class_entry *ce, zend_cl
zend_do_inheritance_ex(ce, parent_ce, 0);
}
-ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, zend_string *key);
+ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, const zend_string *key);
void zend_verify_abstract_class(zend_class_entry *ce);
void zend_build_properties_info_table(zend_class_entry *ce);
ZEND_API zend_class_entry *zend_try_early_bind(zend_class_entry *ce, zend_class_entry *parent_ce, zend_string *lcname, zval *delayed_early_binding);
-void zend_inheritance_check_override(zend_class_entry *ce);
+void zend_inheritance_check_override(const zend_class_entry *ce);
ZEND_API extern zend_class_entry* (*zend_inheritance_cache_get)(zend_class_entry *ce, zend_class_entry *parent, zend_class_entry **traits_and_interfaces);
ZEND_API extern zend_class_entry* (*zend_inheritance_cache_add)(zend_class_entry *ce, zend_class_entry *proto, zend_class_entry *parent, zend_class_entry **traits_and_interfaces, HashTable *dependencies);
@@ -53,7 +53,7 @@ typedef enum {
ZEND_API zend_inheritance_status zend_verify_property_hook_variance(const zend_property_info *prop_info, const zend_function *func);
ZEND_API ZEND_COLD ZEND_NORETURN void zend_hooked_property_variance_error(const zend_property_info *prop_info);
ZEND_API ZEND_COLD ZEND_NORETURN void zend_hooked_property_variance_error_ex(zend_string *value_param_name, zend_string *class_name, zend_string *prop_name);
-ZEND_API void zend_verify_hooked_property(zend_class_entry *ce, zend_property_info *prop_info, zend_string *prop_name);
+ZEND_API void zend_verify_hooked_property(const zend_class_entry *ce, zend_property_info *prop_info, zend_string *prop_name);
END_EXTERN_C()
| diff --git a/Zend/zend_inheritance.c b/Zend/zend_inheritance.c
index 8747e11d151f..53cd8533fd3e 100644
--- a/Zend/zend_inheritance.c
+++ b/Zend/zend_inheritance.c
@@ -96,7 +96,7 @@ static void zend_type_copy_ctor(zend_type *const type, bool use_arena, bool pers
-static zend_function *zend_duplicate_internal_function(zend_function *func, const zend_class_entry *ce) /* {{{ */
+static zend_function *zend_duplicate_internal_function(const zend_function *func, const zend_class_entry *ce) /* {{{ */
zend_function *new_function;
@@ -310,7 +310,7 @@ static zend_class_entry *lookup_class(zend_class_entry *scope, zend_string *name
/* Instanceof that's safe to use on unlinked classes. */
-static bool unlinked_instanceof(zend_class_entry *ce1, const zend_class_entry *ce2) {
+static bool unlinked_instanceof(const zend_class_entry *ce1, const zend_class_entry *ce2) {
if (ce1 == ce2) {
@@ -347,7 +347,7 @@ static bool unlinked_instanceof(zend_class_entry *ce1, const zend_class_entry *c
} else {
for (i = 0; i < ce1->num_interfaces; i++) {
- zend_class_entry *ce = zend_lookup_class_ex(
+ const zend_class_entry *ce = zend_lookup_class_ex(
ce1->interface_names[i].name, ce1->interface_names[i].lc_name,
ZEND_FETCH_CLASS_ALLOW_UNLINKED | ZEND_FETCH_CLASS_NO_AUTOLOAD);
/* Avoid recursing if class implements itself. */
@@ -362,7 +362,7 @@ static bool unlinked_instanceof(zend_class_entry *ce1, const zend_class_entry *c
static bool zend_type_permits_self(
- zend_type type, zend_class_entry *scope, zend_class_entry *self) {
+ zend_type type, const zend_class_entry *scope, zend_class_entry *self) {
if (ZEND_TYPE_FULL_MASK(type) & MAY_BE_OBJECT) {
@@ -374,7 +374,7 @@ static bool zend_type_permits_self(
ZEND_TYPE_FOREACH(type, single_type) {
if (ZEND_TYPE_HAS_NAME(*single_type)) {
zend_string *name = resolve_class_name(scope, ZEND_TYPE_NAME(*single_type));
- zend_class_entry *ce = lookup_class(self, name);
+ const zend_class_entry *ce = lookup_class(self, name);
if (ce && unlinked_instanceof(self, ce)) {
return 1;
@@ -584,7 +584,7 @@ static inheritance_status zend_is_class_subtype_of_type(
return is_intersection ? INHERITANCE_SUCCESS : INHERITANCE_ERROR;
+static zend_string *get_class_from_type(const zend_class_entry *scope, zend_type single_type) {
if (ZEND_TYPE_HAS_NAME(single_type)) {
return resolve_class_name(scope, ZEND_TYPE_NAME(single_type));
@@ -706,7 +706,6 @@ ZEND_API inheritance_status zend_perform_covariant_type_check(
- zend_type *single_type;
inheritance_status early_exit_status;
bool have_unresolved = false;
@@ -728,6 +727,7 @@ ZEND_API inheritance_status zend_perform_covariant_type_check(
* We need to iterate over fe_type (U_i) first and the logic is independent of
* whether proto_type is a union or intersection (only the inner check differs). */
early_exit_status = INHERITANCE_ERROR;
+ zend_type *single_type;
ZEND_TYPE_FOREACH(fe_type, single_type) {
inheritance_status status;
/* Union has an intersection type as it's member */
@@ -790,7 +790,7 @@ static inheritance_status zend_do_perform_implementation_check(
const zend_function *fe, zend_class_entry *fe_scope,
const zend_function *proto, zend_class_entry *proto_scope) /* {{{ */
- uint32_t i, num_args, proto_num_args, fe_num_args;
+ uint32_t num_args, proto_num_args, fe_num_args;
inheritance_status status, local_status;
bool proto_is_variadic, fe_is_variadic;
@@ -831,7 +831,7 @@ static inheritance_status zend_do_perform_implementation_check(
num_args = MAX(proto_num_args, fe_num_args);
status = INHERITANCE_SUCCESS;
zend_arg_info *proto_arg_info =
i < proto_num_args ? &proto->common.arg_info[i] :
proto_is_variadic ? &proto->common.arg_info[proto_num_args - 1] : NULL;
@@ -933,7 +933,7 @@ static ZEND_COLD zend_string *zend_get_function_declaration(
smart_str_appendc(&str, '(');
if (fptr->common.arg_info) {
- uint32_t i, num_args, required;
+ uint32_t num_args, required;
zend_arg_info *arg_info = fptr->common.arg_info;
required = fptr->common.required_num_args;
@@ -941,7 +941,7 @@ static ZEND_COLD zend_string *zend_get_function_declaration(
if (fptr->common.fn_flags & ZEND_ACC_VARIADIC) {
num_args++;
+ for (uint32_t i = 0; i < num_args;) {
zend_append_type_hint(&str, scope, arg_info, 0);
if (ZEND_ARG_SEND_MODE(arg_info)) {
@@ -973,7 +973,7 @@ static ZEND_COLD zend_string *zend_get_function_declaration(
{
uint32_t idx = i;
zend_op *op = fptr->op_array.opcodes;
- zend_op *end = op + fptr->op_array.last;
++idx;
while (op < end) {
@@ -1366,7 +1366,7 @@ static inheritance_status verify_property_type_compatibility(
return INHERITANCE_SUCCESS;
-static bool property_has_operation(zend_property_info *prop_info, zend_property_hook_kind kind)
+static bool property_has_operation(const zend_property_info *prop_info, zend_property_hook_kind kind)
return (!(prop_info->flags & ZEND_ACC_VIRTUAL)
&& (kind == ZEND_PROPERTY_HOOK_GET || !(prop_info->flags & ZEND_ACC_READONLY)))
@@ -1451,10 +1451,9 @@ static prop_variance prop_get_variance(const zend_property_info *prop_info) {
static void do_inherit_property(zend_property_info *parent_info, zend_string *key, zend_class_entry *ce) /* {{{ */
zval *child = zend_hash_find_known_hash(&ce->properties_info, key);
- zend_property_info *child_info;
if (UNEXPECTED(child)) {
- child_info = Z_PTR_P(child);
+ zend_property_info *child_info = Z_PTR_P(child);
if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_CHANGED)) {
child_info->flags |= ZEND_ACC_CHANGED;
@@ -1596,7 +1595,6 @@ static void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_en
/* expects interface to be contained in ce's interface list already */
uint32_t i, ce_num, if_num = iface->num_interfaces;
- zend_class_entry *entry;
ce_num = ce->num_interfaces;
@@ -1608,7 +1606,7 @@ static void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_en
/* Inherit the interfaces, only if they're not already inherited by the class */
while (if_num--) {
- entry = iface->interfaces[if_num];
+ zend_class_entry *entry = iface->interfaces[if_num];
for (i = 0; i < ce_num; i++) {
if (ce->interfaces[i] == entry) {
break;
@@ -1651,7 +1649,7 @@ static inheritance_status class_constant_types_compatible(const zend_class_const
- zend_class_entry *ce, zend_class_constant *parent_constant, zend_string *name);
+ zend_class_entry *ce, const zend_class_constant *parent_constant, zend_string *name);
static void do_inherit_class_constant(zend_string *name, zend_class_constant *parent_const, zend_class_entry *ce) /* {{{ */
@@ -1724,7 +1722,7 @@ void zend_build_properties_info_table(zend_class_entry *ce)
} ZEND_HASH_FOREACH_END();
-ZEND_API void zend_verify_hooked_property(zend_class_entry *ce, zend_property_info *prop_info, zend_string *prop_name)
+ZEND_API void zend_verify_hooked_property(const zend_class_entry *ce, zend_property_info *prop_info, zend_string *prop_name)
if (!prop_info->hooks) {
@@ -1748,7 +1746,7 @@ ZEND_API void zend_verify_hooked_property(zend_class_entry *ce, zend_property_in
ZVAL_NULL(&ce->default_properties_table[OBJ_PROP_TO_NUM(prop_info->offset)]);
for (uint32_t i = 0; i < ZEND_PROPERTY_HOOK_COUNT; i++) {
- zend_function *func = prop_info->hooks[i];
+ const zend_function *func = prop_info->hooks[i];
if (func) {
if ((zend_property_hook_kind)i == ZEND_PROPERTY_HOOK_GET
&& (func->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE)
@@ -1830,7 +1828,6 @@ static void zend_link_hooked_object_iter(zend_class_entry *ce) {
ZEND_API void zend_do_inheritance_ex(zend_class_entry *ce, zend_class_entry *parent_ce, bool checked) /* {{{ */
- zend_function *func;
if (UNEXPECTED(ce->ce_flags & ZEND_ACC_INTERFACE)) {
@@ -2021,6 +2018,7 @@ ZEND_API void zend_do_inheritance_ex(zend_class_entry *ce, zend_class_entry *par
if (!checked) {
flags |= ZEND_INHERITANCE_CHECK_PROTO | ZEND_INHERITANCE_CHECK_VISIBILITY;
+ zend_function *func;
ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&parent_ce->function_table, key, func) {
do_inherit_method(key, func, ce, 0, flags);
} ZEND_HASH_FOREACH_END();
@@ -2079,7 +2077,7 @@ static zend_always_inline bool check_trait_property_or_constant_value_compatibil
/** @return bool Returns true if the class constant should be inherited, i.e. whether it doesn't already exist. */
- zend_class_entry *ce, zend_class_constant *parent_constant, zend_string *name
+ zend_class_entry *ce, const zend_class_constant *parent_constant, zend_string *name
) {
zval *zv = zend_hash_find_known_hash(&ce->constants_table, name);
if (zv == NULL) {
@@ -2126,7 +2124,7 @@ static bool do_inherit_constant_check(
+static void do_inherit_iface_constant(zend_string *name, zend_class_constant *c, zend_class_entry *ce, const zend_class_entry *iface) /* {{{ */
if (do_inherit_constant_check(ce, c, name)) {
zend_class_constant *ct;
@@ -2196,27 +2194,27 @@ static void do_interface_implementation(zend_class_entry *ce, zend_class_entry *
ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface) /* {{{ */
- uint32_t i, ignore = 0;
+ bool ignore = false;
uint32_t current_iface_num = ce->num_interfaces;
uint32_t parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0;
- zend_string *key;
- zend_class_constant *c;
ZEND_ASSERT(ce->ce_flags & ZEND_ACC_LINKED);
if (ce->interfaces[i] == NULL) {
memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i));
i--;
} else if (ce->interfaces[i] == iface) {
if (EXPECTED(i < parent_iface_num)) {
- ignore = 1;
+ ignore = true;
} else {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name));
if (ignore) {
+ zend_string *key;
+ zend_class_constant *c;
/* Check for attempt to redeclare interface constants */
ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&iface->constants_table, key, c) {
do_inherit_constant_check(ce, c, key);
@@ -2238,15 +2236,14 @@ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry
static void zend_do_implement_interfaces(zend_class_entry *ce, zend_class_entry **interfaces) /* {{{ */
- zend_class_entry *iface;
uint32_t num_parent_interfaces = ce->parent ? ce->parent->num_interfaces : 0;
uint32_t num_interfaces = num_parent_interfaces;
zend_class_constant *c;
- uint32_t i, j;
+ uint32_t i;
for (i = 0; i < ce->num_interfaces; i++) {
- iface = interfaces[num_parent_interfaces + i];
+ zend_class_entry *iface = interfaces[num_parent_interfaces + i];
if (!(iface->ce_flags & ZEND_ACC_LINKED)) {
add_dependency_obligation(ce, iface);
@@ -2255,7 +2252,7 @@ static void zend_do_implement_interfaces(zend_class_entry *ce, zend_class_entry
zend_error_noreturn(E_ERROR, "%s cannot implement %s - it is not an interface", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name));
return;
- for (j = 0; j < num_interfaces; j++) {
+ for (uint32_t j = 0; j < num_interfaces; j++) {
if (interfaces[j] == iface) {
if (j >= num_parent_interfaces) {
efree(interfaces);
@@ -2304,7 +2301,7 @@ static void zend_do_implement_interfaces(zend_class_entry *ce, zend_class_entry
-void zend_inheritance_check_override(zend_class_entry *ce)
+void zend_inheritance_check_override(const zend_class_entry *ce)
zend_function *f;
@@ -2426,7 +2423,7 @@ static void zend_fixup_trait_method(zend_function *fn, zend_class_entry *ce) /*
-static void zend_traits_check_private_final_inheritance(uint32_t original_fn_flags, zend_function *fn_copy, zend_string *name)
+static void zend_traits_check_private_final_inheritance(uint32_t original_fn_flags, const zend_function *fn_copy, const zend_string *name)
/* If the function was originally already private+final, then it will have
* already been warned about. Only emit this error when the used trait method
@@ -2442,7 +2439,6 @@ static void zend_traits_check_private_final_inheritance(uint32_t original_fn_fla
static void zend_traits_copy_functions(zend_string *fnname, zend_function *fn, zend_class_entry *ce, HashTable *exclude_table, zend_class_entry **aliases) /* {{{ */
zend_trait_alias *alias, **alias_ptr;
- zend_string *lcname;
zend_function fn_copy;
int i;
@@ -2466,7 +2462,7 @@ static void zend_traits_copy_functions(zend_string *fnname, zend_function *fn, z
zend_traits_check_private_final_inheritance(fn->common.fn_flags, &fn_copy, alias->alias);
- lcname = zend_string_tolower(alias->alias);
+ zend_string *lcname = zend_string_tolower(alias->alias);
zend_add_trait_method(ce, alias->alias, lcname, &fn_copy);
zend_string_release_ex(lcname, 0);
@@ -2510,16 +2506,14 @@ static void zend_traits_copy_functions(zend_string *fnname, zend_function *fn, z
-static uint32_t zend_check_trait_usage(zend_class_entry *ce, zend_class_entry *trait, zend_class_entry **traits) /* {{{ */
+static uint32_t zend_check_trait_usage(const zend_class_entry *ce, const zend_class_entry *trait, zend_class_entry **traits) /* {{{ */
- uint32_t i;
if (UNEXPECTED((trait->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT)) {
zend_error_noreturn(E_COMPILE_ERROR, "Class %s is not a trait, Only traits may be used in 'as' and 'insteadof' statements", ZSTR_VAL(trait->name));
return 0;
if (traits[i] == trait) {
return i;
@@ -2532,7 +2526,6 @@ static uint32_t zend_check_trait_usage(zend_class_entry *ce, zend_class_entry *t
static void zend_traits_init_trait_structures(zend_class_entry *ce, zend_class_entry **traits, HashTable ***exclude_tables_ptr, zend_class_entry ***aliases_ptr) /* {{{ */
size_t i, j = 0;
- zend_trait_precedence **precedences;
zend_trait_precedence *cur_precedence;
zend_trait_method_reference *cur_method_ref;
zend_string *lc_trait_name;
@@ -2545,7 +2538,7 @@ static void zend_traits_init_trait_structures(zend_class_entry *ce, zend_class_e
if (ce->trait_precedences) {
exclude_tables = ecalloc(ce->num_traits, sizeof(HashTable*));
- precedences = ce->trait_precedences;
ce->trait_precedences = NULL;
while ((cur_precedence = precedences[i])) {
/** Resolve classes for all precedence operations. */
@@ -2619,7 +2612,7 @@ static void zend_traits_init_trait_structures(zend_class_entry *ce, zend_class_e
aliases = ecalloc(i, sizeof(zend_class_entry*));
while (ce->trait_aliases[i]) {
- zend_trait_alias *cur_alias = ce->trait_aliases[i];
+ const zend_trait_alias *cur_alias = ce->trait_aliases[i];
cur_method_ref = &ce->trait_aliases[i]->trait_method;
lcname = zend_string_tolower(cur_method_ref->method_name);
if (cur_method_ref->class_name) {
@@ -2736,10 +2729,8 @@ static const zend_class_entry* find_first_constant_definition(const zend_class_e
* process like this is needed to find the location of the first definition
* of the constant from traits.
&& zend_hash_exists(&traits[i]->constants_table, constant_name)) {
@@ -2806,9 +2797,7 @@ static bool do_trait_constant_check(
static void zend_do_traits_constant_binding(zend_class_entry *ce, zend_class_entry **traits) /* {{{ */
zend_string *constant_name;
zend_class_constant *constant;
@@ -2850,10 +2839,8 @@ static void zend_do_traits_constant_binding(zend_class_entry *ce, zend_class_ent
static const zend_class_entry* find_first_property_definition(const zend_class_entry *ce, zend_class_entry **traits, size_t current_trait, zend_string *prop_name, const zend_class_entry *colliding_ce) /* {{{ */
&& zend_hash_exists(&traits[i]->properties_info, prop_name)) {
@@ -2867,20 +2854,17 @@ static const zend_class_entry* find_first_property_definition(const zend_class_e
static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_entry **traits) /* {{{ */
const zend_property_info *colliding_prop;
- zend_property_info *new_prop;
zend_string* prop_name;
zval* prop_value;
/* In the following steps the properties are inserted into the property table
* for that, a very strict approach is applied:
* - check for compatibility, if not compatible with any property in class -> fatal
* - if compatible, then strict notice
if (!traits[i]) {
continue;
@@ -2960,12 +2944,13 @@ static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_ent
prop_value = &tmp_prop_value;
ZVAL_UNDEF(&tmp_prop_value);
- doc_comment = property_info->doc_comment ? zend_string_copy(property_info->doc_comment) : NULL;
+
+ zend_string *doc_comment = property_info->doc_comment ? zend_string_copy(property_info->doc_comment) : NULL;
zend_type type = property_info->type;
/* Assumption: only userland classes can use traits, as such the type must be arena allocated */
zend_type_copy_ctor(&type, /* use arena */ true, /* persistent */ false);
- new_prop = zend_declare_typed_property(ce, prop_name, prop_value, flags, doc_comment, type);
+ zend_property_info *new_prop = zend_declare_typed_property(ce, prop_name, prop_value, flags, doc_comment, type);
if (property_info->attributes) {
new_prop->attributes = property_info->attributes;
@@ -2978,9 +2963,9 @@ static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_ent
zend_function **hooks = new_prop->hooks =
zend_arena_alloc(&CG(arena), ZEND_PROPERTY_HOOK_STRUCT_SIZE);
memcpy(hooks, property_info->hooks, ZEND_PROPERTY_HOOK_STRUCT_SIZE);
- for (uint32_t i = 0; i < ZEND_PROPERTY_HOOK_COUNT; i++) {
- if (hooks[i]) {
- zend_function *old_fn = hooks[i];
+ for (uint32_t j = 0; j < ZEND_PROPERTY_HOOK_COUNT; j++) {
+ if (hooks[j]) {
+ zend_function *old_fn = hooks[j];
/* Hooks are not yet supported for internal properties. */
ZEND_ASSERT(ZEND_USER_CODE(old_fn->type));
@@ -2995,7 +2980,7 @@ static void zend_do_traits_property_binding(zend_class_entry *ce, zend_class_ent
zend_fixup_trait_method(new_fn, ce);
- hooks[i] = new_fn;
+ hooks[j] = new_fn;
}
}
ce->ce_flags |= ZEND_ACC_USE_GUARDS;
@@ -3221,7 +3206,7 @@ static void add_property_hook_obligation(
static void resolve_delayed_variance_obligations(zend_class_entry *ce);
-static void check_variance_obligation(variance_obligation *obligation) {
+static void check_variance_obligation(const variance_obligation *obligation) {
if (obligation->type == OBLIGATION_DEPENDENCY) {
zend_class_entry *dependency_ce = obligation->dependency_ce;
if (dependency_ce->ce_flags & ZEND_ACC_UNRESOLVED_VARIANCE) {
@@ -3260,7 +3245,7 @@ static void check_variance_obligation(variance_obligation *obligation) {
-static void load_delayed_classes(zend_class_entry *ce) {
+static void load_delayed_classes(const zend_class_entry *ce) {
HashTable *delayed_autoloads = CG(delayed_autoloads);
if (!delayed_autoloads) {
@@ -3289,11 +3274,11 @@ static void load_delayed_classes(zend_class_entry *ce) {
static void resolve_delayed_variance_obligations(zend_class_entry *ce) {
- HashTable *all_obligations = CG(delayed_variance_obligations), *obligations;
+ HashTable *all_obligations = CG(delayed_variance_obligations);
zend_ulong num_key = (zend_ulong) (uintptr_t) ce;
ZEND_ASSERT(all_obligations != NULL);
- obligations = zend_hash_index_find_ptr(all_obligations, num_key);
+ const HashTable *obligations = zend_hash_index_find_ptr(all_obligations, num_key);
ZEND_ASSERT(obligations != NULL);
variance_obligation *obligation;
@@ -3327,7 +3312,7 @@ static void check_unrecoverable_load_failure(const zend_class_entry *ce) {
} while (0)
static zend_op_array *zend_lazy_method_load(
- zend_op_array *op_array, zend_class_entry *ce, const zend_class_entry *pce) {
ZEND_ASSERT(op_array->type == ZEND_USER_FUNCTION);
ZEND_ASSERT(op_array->scope == pce);
ZEND_ASSERT(op_array->prototype == NULL);
@@ -3341,12 +3326,10 @@ static zend_op_array *zend_lazy_method_load(
return new_op_array;
-static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
+static zend_class_entry *zend_lazy_class_load(const zend_class_entry *pce)
- zend_class_entry *ce;
- Bucket *p, *end;
- ce = zend_arena_alloc(&CG(arena), sizeof(zend_class_entry));
memcpy(ce, pce, sizeof(zend_class_entry));
ce->ce_flags &= ~ZEND_ACC_IMMUTABLE;
ce->refcount = 1;
@@ -3361,7 +3344,7 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
if (ce->default_properties_table) {
zval *dst = emalloc(sizeof(zval) * ce->default_properties_count);
zval *src = ce->default_properties_table;
+ const zval *end = src + ce->default_properties_count;
ce->default_properties_table = dst;
@@ -3372,11 +3355,11 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
/* methods */
ce->function_table.pDestructor = ZEND_FUNCTION_DTOR;
if (!(HT_FLAGS(&ce->function_table) & HASH_FLAG_UNINITIALIZED)) {
- p = emalloc(HT_SIZE(&ce->function_table));
+ Bucket *p = emalloc(HT_SIZE(&ce->function_table));
memcpy(p, HT_GET_DATA_ADDR(&ce->function_table), HT_USED_SIZE(&ce->function_table));
HT_SET_DATA_ADDR(&ce->function_table, p);
p = ce->function_table.arData;
- end = p + ce->function_table.nNumUsed;
zend_op_array *op_array = Z_PTR(p->val);
zend_op_array *new_op_array = Z_PTR(p->val) = zend_lazy_method_load(op_array, ce, pce);
@@ -3401,7 +3384,7 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
if (ce->default_static_members_table) {
zval *dst = emalloc(sizeof(zval) * ce->default_static_members_count);
zval *src = ce->default_static_members_table;
- zval *end = src + ce->default_static_members_count;
+ const zval *end = src + ce->default_static_members_count;
ce->default_static_members_table = dst;
@@ -3412,15 +3395,15 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
/* properties_info */
if (!(HT_FLAGS(&ce->properties_info) & HASH_FLAG_UNINITIALIZED)) {
- p = emalloc(HT_SIZE(&ce->properties_info));
+ Bucket *p = emalloc(HT_SIZE(&ce->properties_info));
memcpy(p, HT_GET_DATA_ADDR(&ce->properties_info), HT_USED_SIZE(&ce->properties_info));
HT_SET_DATA_ADDR(&ce->properties_info, p);
p = ce->properties_info.arData;
- end = p + ce->properties_info.nNumUsed;
+ const Bucket *end = p + ce->properties_info.nNumUsed;
- zend_property_info *prop_info, *new_prop_info;
+ zend_property_info *new_prop_info;
+ const zend_property_info *prop_info = Z_PTR(p->val);
ZEND_ASSERT(prop_info->ce == pce);
ZEND_ASSERT(prop_info->prototype == prop_info);
new_prop_info= zend_arena_alloc(&CG(arena), sizeof(zend_property_info));
@@ -3448,15 +3431,15 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
/* constants table */
if (!(HT_FLAGS(&ce->constants_table) & HASH_FLAG_UNINITIALIZED)) {
- p = emalloc(HT_SIZE(&ce->constants_table));
+ Bucket *p = emalloc(HT_SIZE(&ce->constants_table));
memcpy(p, HT_GET_DATA_ADDR(&ce->constants_table), HT_USED_SIZE(&ce->constants_table));
HT_SET_DATA_ADDR(&ce->constants_table, p);
p = ce->constants_table.arData;
- end = p + ce->constants_table.nNumUsed;
- zend_class_constant *c, *new_c;
+ zend_class_constant *new_c;
- c = Z_PTR(p->val);
+ const zend_class_constant *c = Z_PTR(p->val);
ZEND_ASSERT(c->ce == pce);
new_c = zend_arena_alloc(&CG(arena), sizeof(zend_class_constant));
Z_PTR(p->val) = new_c;
@@ -3481,7 +3464,7 @@ static zend_class_entry *zend_lazy_class_load(zend_class_entry *pce)
} while (0)
#endif
-ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, zend_string *key) /* {{{ */
+ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, const zend_string *key) /* {{{ */
/* Load parent/interface dependencies first, so we can still gracefully abort linking
* with an exception and remove the class from the class table. This is only possible
@@ -3784,7 +3767,7 @@ ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string
/* Check whether early binding is prevented due to unresolved types in inheritance checks. */
+static inheritance_status zend_can_early_bind(zend_class_entry *ce, const zend_class_entry *parent_ce) /* {{{ */
zend_function *parent_func;
diff --git a/Zend/zend_inheritance.h b/Zend/zend_inheritance.h
index 477874181e41..7171a9385f3b 100644
--- a/Zend/zend_inheritance.h
+++ b/Zend/zend_inheritance.h
@@ -32,13 +32,13 @@ static zend_always_inline void zend_do_inheritance(zend_class_entry *ce, zend_cl
zend_do_inheritance_ex(ce, parent_ce, 0);
-ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, zend_string *key);
+ZEND_API zend_class_entry *zend_do_link_class(zend_class_entry *ce, zend_string *lc_parent_name, const zend_string *key);
void zend_verify_abstract_class(zend_class_entry *ce);
void zend_build_properties_info_table(zend_class_entry *ce);
ZEND_API zend_class_entry *zend_try_early_bind(zend_class_entry *ce, zend_class_entry *parent_ce, zend_string *lcname, zval *delayed_early_binding);
-void zend_inheritance_check_override(zend_class_entry *ce);
+void zend_inheritance_check_override(const zend_class_entry *ce);
ZEND_API extern zend_class_entry* (*zend_inheritance_cache_get)(zend_class_entry *ce, zend_class_entry *parent, zend_class_entry **traits_and_interfaces);
ZEND_API extern zend_class_entry* (*zend_inheritance_cache_add)(zend_class_entry *ce, zend_class_entry *proto, zend_class_entry *parent, zend_class_entry **traits_and_interfaces, HashTable *dependencies);
@@ -53,7 +53,7 @@ typedef enum {
ZEND_API zend_inheritance_status zend_verify_property_hook_variance(const zend_property_info *prop_info, const zend_function *func);
ZEND_API ZEND_COLD ZEND_NORETURN void zend_hooked_property_variance_error(const zend_property_info *prop_info);
ZEND_API ZEND_COLD ZEND_NORETURN void zend_hooked_property_variance_error_ex(zend_string *value_param_name, zend_string *class_name, zend_string *prop_name);
+ZEND_API void zend_verify_hooked_property(const zend_class_entry *ce, zend_property_info *prop_info, zend_string *prop_name);
END_EXTERN_C() | [
"-static zend_string *get_class_from_type(zend_class_entry *scope, zend_type single_type) {",
"-\tfor (i = 0; i < num_args; i++) {",
"+\tfor (uint32_t i = 0; i < num_args; i++) {",
"-\t\tfor (i = 0; i < num_args;) {",
"+\t\t\t\t\t\tconst zend_op *end = op + fptr->op_array.last;",
"-static void do_inherit_iface_constant(zend_string *name, zend_class_constant *c, zend_class_entry *ce, zend_class_entry *iface) /* {{{ */",
"-\tfor (i = 0; i < ce->num_interfaces; i++) {",
"+\tfor (uint32_t i = 0; i < ce->num_interfaces; i++) {",
"+\t\tzend_trait_precedence **precedences = ce->trait_precedences;",
"-\tzend_string *doc_comment;",
"+\t\tconst zend_op_array *op_array, zend_class_entry *ce, const zend_class_entry *pce) {",
"+\tzend_class_entry *ce = zend_arena_alloc(&CG(arena), sizeof(zend_class_entry));",
"-\t\tzval *end = src + ce->default_properties_count;",
"+\t\tconst Bucket *end = p + ce->function_table.nNumUsed;",
"-\t\t\tprop_info = Z_PTR(p->val);",
"+\t\tconst Bucket *end = p + ce->constants_table.nNumUsed;",
"-static inheritance_status zend_can_early_bind(zend_class_entry *ce, zend_class_entry *parent_ce) /* {{{ */",
"-ZEND_API void zend_verify_hooked_property(zend_class_entry *ce, zend_property_info *prop_info, zend_string *prop_name);"
] | [
53,
87,
88,
105,
115,
213,
231,
232,
345,
403,
490,
503,
513,
528,
556,
571,
594,
623
] | {
"additions": 71,
"author": "Girgias",
"deletions": 88,
"html_url": "https://github.com/php/php-src/pull/18253",
"issue_id": 18253,
"merged_at": "2025-04-05T14:47:52Z",
"omission_probability": 0.1,
"pr_number": 18253,
"repo": "php/php-src",
"title": "Zend/zend_inheritance: Minor refactorings",
"total_changes": 159
} |
765 | diff --git a/Zend/zend_enum.c b/Zend/zend_enum.c
index ccafca48fe9b..6baa34cc5012 100644
--- a/Zend/zend_enum.c
+++ b/Zend/zend_enum.c
@@ -610,8 +610,7 @@ ZEND_API void zend_enum_add_case_cstr(zend_class_entry *ce, const char *name, zv
zend_string_release(name_str);
}
-ZEND_API zend_object *zend_enum_get_case(zend_class_entry *ce, zend_string *name) {
- zend_class_constant *c = zend_hash_find_ptr(CE_CONSTANTS_TABLE(ce), name);
+static zend_object *zend_enum_case_from_class_constant(zend_class_constant *c) {
ZEND_ASSERT(c && "Must be a valid enum case");
ZEND_ASSERT(ZEND_CLASS_CONST_FLAGS(c) & ZEND_CLASS_CONST_IS_CASE);
@@ -624,9 +623,12 @@ ZEND_API zend_object *zend_enum_get_case(zend_class_entry *ce, zend_string *name
return Z_OBJ(c->value);
}
+ZEND_API zend_object *zend_enum_get_case(zend_class_entry *ce, zend_string *name) {
+ zend_class_constant *c = zend_hash_find_ptr(CE_CONSTANTS_TABLE(ce), name);
+ return zend_enum_case_from_class_constant(c);
+}
+
ZEND_API zend_object *zend_enum_get_case_cstr(zend_class_entry *ce, const char *name) {
- zend_string *name_str = zend_string_init(name, strlen(name), 0);
- zend_object *result = zend_enum_get_case(ce, name_str);
- zend_string_release(name_str);
- return result;
+ zend_class_constant *c = zend_hash_str_find_ptr(CE_CONSTANTS_TABLE(ce), name, strlen(name));
+ return zend_enum_case_from_class_constant(c);
}
| diff --git a/Zend/zend_enum.c b/Zend/zend_enum.c
index ccafca48fe9b..6baa34cc5012 100644
--- a/Zend/zend_enum.c
+++ b/Zend/zend_enum.c
@@ -610,8 +610,7 @@ ZEND_API void zend_enum_add_case_cstr(zend_class_entry *ce, const char *name, zv
zend_string_release(name_str);
-ZEND_API zend_object *zend_enum_get_case(zend_class_entry *ce, zend_string *name) {
- zend_class_constant *c = zend_hash_find_ptr(CE_CONSTANTS_TABLE(ce), name);
+static zend_object *zend_enum_case_from_class_constant(zend_class_constant *c) {
ZEND_ASSERT(c && "Must be a valid enum case");
ZEND_ASSERT(ZEND_CLASS_CONST_FLAGS(c) & ZEND_CLASS_CONST_IS_CASE);
@@ -624,9 +623,12 @@ ZEND_API zend_object *zend_enum_get_case(zend_class_entry *ce, zend_string *name
return Z_OBJ(c->value);
+ZEND_API zend_object *zend_enum_get_case(zend_class_entry *ce, zend_string *name) {
+ zend_class_constant *c = zend_hash_find_ptr(CE_CONSTANTS_TABLE(ce), name);
+
ZEND_API zend_object *zend_enum_get_case_cstr(zend_class_entry *ce, const char *name) {
- zend_string *name_str = zend_string_init(name, strlen(name), 0);
- zend_object *result = zend_enum_get_case(ce, name_str);
- zend_string_release(name_str);
+ zend_class_constant *c = zend_hash_str_find_ptr(CE_CONSTANTS_TABLE(ce), name, strlen(name)); | [
"+}",
"-\treturn result;"
] | [
21,
27
] | {
"additions": 8,
"author": "nielsdos",
"deletions": 6,
"html_url": "https://github.com/php/php-src/pull/18239",
"issue_id": 18239,
"merged_at": "2025-04-04T16:02:48Z",
"omission_probability": 0.1,
"pr_number": 18239,
"repo": "php/php-src",
"title": "Avoid allocation in zend_enum_get_case_cstr()",
"total_changes": 14
} |
766 | diff --git a/docs/source/miscellaneous/stubs.rst b/docs/source/miscellaneous/stubs.rst
index 385eddc5be72f..3899fe3084196 100644
--- a/docs/source/miscellaneous/stubs.rst
+++ b/docs/source/miscellaneous/stubs.rst
@@ -13,11 +13,11 @@ code, but instead contain empty function and method bodies. A very basic stub lo
/** @var float */
const WEIGHT = 6.8;
- class Atmopshere {
+ class Atmosphere {
public function calculateBar(): float {}
}
- function fahrenheitToCelcius(float $fahrenheitToCelcius): float {}
+ function fahrenheitToCelsius(float $fahrenheitToCelsius): float {}
Any kind of symbol can be declared via stubs. Every type can be used, with the exception of
disjunctive normal form (DNF) types. Additional meta information can be added via PHPDoc blocks or
@@ -33,17 +33,17 @@ using namespace blocks:
/** @var float */
const WEIGHT_TON = 6.8;
- class Atmopshere {
+ class Atmosphere {
public function calculateBar(): float {}
}
}
namespace Algorithms {
- function fahrenheitToCelcius(float $fahrenheit): float {}
+ function fahrenheitToCelsius(float $fahrenheit): float {}
}
The above example declares the global constants ``ANIMAL`` and ``WEIGHT_TON``, and the class
-``Atmopshere`` in the top-level namespace. The ``fahrenheitToCelcius()`` function is declared to be
+``Atmosphere`` in the top-level namespace. The ``fahrenheitToCelsius()`` function is declared to be
in the ``Algorithms`` namespace.
********************
@@ -77,11 +77,11 @@ The arginfo file matching our first example looks like:
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: e4ed788d54a20272a92a3f6618b73d48ec848f97 */
- ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_fahrenheitToCelcius, 0, 1, IS_DOUBLE, 0)
- ZEND_ARG_TYPE_INFO(0, fahrenheitToCelcius, IS_DOUBLE, 0)
+ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_fahrenheitToCelsius, 0, 1, IS_DOUBLE, 0)
+ ZEND_ARG_TYPE_INFO(0, fahrenheitToCelsius, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
- ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Atmopshere_calculateBar, 0, 0, IS_DOUBLE, 0)
+ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Atmosphere_calculateBar, 0, 0, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
The hash that is included in the file makes sure that stub files are not reprocessed unless the stub
@@ -186,24 +186,24 @@ In order to generate these, add the file-level ``@generate-function-entries`` PH
public function calculateBar(): float {}
}
- function fahrenheitToCelcius(float $fahrenheit): float {}
+ function fahrenheitToCelsius(float $fahrenheit): float {}
Now, the following C code is generated:
.. code:: c
- ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_fahrenheitToCelcius, 0, 1, IS_DOUBLE, 0)
+ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_fahrenheitToCelsius, 0, 1, IS_DOUBLE, 0)
ZEND_ARG_TYPE_INFO(0, fahrenheit, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Atmosphere_calculateBar, 0, 0, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
- ZEND_FUNCTION(fahrenheitToCelcius);
+ ZEND_FUNCTION(fahrenheitToCelsius);
ZEND_METHOD(Atmosphere, calculateBar);
static const zend_function_entry ext_functions[] = {
- ZEND_FE(fahrenheitToCelcius, arginfo_fahrenheitToCelcius)
+ ZEND_FE(fahrenheitToCelsius, arginfo_fahrenheitToCelsius)
ZEND_FE_END
};
@@ -762,7 +762,7 @@ Running it with the stub examples that are used in this guide, the following war
Warning: Missing class synopsis for Number
Warning: Missing class synopsis for Elephant
Warning: Missing class synopsis for Atmosphere
- Warning: Missing method synopsis for fahrenheitToCelcius()
+ Warning: Missing method synopsis for fahrenheitToCelsius()
Warning: Missing method synopsis for Atmosphere::calculateBar()
**********************
| diff --git a/docs/source/miscellaneous/stubs.rst b/docs/source/miscellaneous/stubs.rst
index 385eddc5be72f..3899fe3084196 100644
--- a/docs/source/miscellaneous/stubs.rst
+++ b/docs/source/miscellaneous/stubs.rst
@@ -13,11 +13,11 @@ code, but instead contain empty function and method bodies. A very basic stub lo
/** @var float */
const WEIGHT = 6.8;
- class Atmopshere {
+ class Atmosphere {
public function calculateBar(): float {}
- function fahrenheitToCelcius(float $fahrenheitToCelcius): float {}
Any kind of symbol can be declared via stubs. Every type can be used, with the exception of
disjunctive normal form (DNF) types. Additional meta information can be added via PHPDoc blocks or
@@ -33,17 +33,17 @@ using namespace blocks:
/** @var float */
const WEIGHT_TON = 6.8;
- class Atmopshere {
+ class Atmosphere {
public function calculateBar(): float {}
}
namespace Algorithms {
- function fahrenheitToCelcius(float $fahrenheit): float {}
The above example declares the global constants ``ANIMAL`` and ``WEIGHT_TON``, and the class
-``Atmopshere`` in the top-level namespace. The ``fahrenheitToCelcius()`` function is declared to be
+``Atmosphere`` in the top-level namespace. The ``fahrenheitToCelsius()`` function is declared to be
in the ``Algorithms`` namespace.
********************
@@ -77,11 +77,11 @@ The arginfo file matching our first example looks like:
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: e4ed788d54a20272a92a3f6618b73d48ec848f97 */
- ZEND_ARG_TYPE_INFO(0, fahrenheitToCelcius, IS_DOUBLE, 0)
+ ZEND_ARG_TYPE_INFO(0, fahrenheitToCelsius, IS_DOUBLE, 0)
- ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Atmopshere_calculateBar, 0, 0, IS_DOUBLE, 0)
+ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Atmosphere_calculateBar, 0, 0, IS_DOUBLE, 0)
The hash that is included in the file makes sure that stub files are not reprocessed unless the stub
@@ -186,24 +186,24 @@ In order to generate these, add the file-level ``@generate-function-entries`` PH
public function calculateBar(): float {}
- function fahrenheitToCelcius(float $fahrenheit): float {}
+ function fahrenheitToCelsius(float $fahrenheit): float {}
Now, the following C code is generated:
.. code:: c
ZEND_ARG_TYPE_INFO(0, fahrenheit, IS_DOUBLE, 0)
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Atmosphere_calculateBar, 0, 0, IS_DOUBLE, 0)
- ZEND_FUNCTION(fahrenheitToCelcius);
+ ZEND_FUNCTION(fahrenheitToCelsius);
ZEND_METHOD(Atmosphere, calculateBar);
static const zend_function_entry ext_functions[] = {
- ZEND_FE(fahrenheitToCelcius, arginfo_fahrenheitToCelcius)
+ ZEND_FE(fahrenheitToCelsius, arginfo_fahrenheitToCelsius)
ZEND_FE_END
};
@@ -762,7 +762,7 @@ Running it with the stub examples that are used in this guide, the following war
Warning: Missing class synopsis for Number
Warning: Missing class synopsis for Elephant
Warning: Missing class synopsis for Atmosphere
+ Warning: Missing method synopsis for fahrenheitToCelsius()
Warning: Missing method synopsis for Atmosphere::calculateBar()
********************** | [
"+ function fahrenheitToCelsius(float $fahrenheitToCelsius): float {}",
"+ function fahrenheitToCelsius(float $fahrenheit): float {}",
"- Warning: Missing method synopsis for fahrenheitToCelcius()"
] | [
14,
30,
87
] | {
"additions": 13,
"author": "jbampton",
"deletions": 13,
"html_url": "https://github.com/php/php-src/pull/18220",
"issue_id": 18220,
"merged_at": "2025-04-01T10:51:02Z",
"omission_probability": 0.1,
"pr_number": 18220,
"repo": "php/php-src",
"title": "docs: fix spelling in `stubs.rst`",
"total_changes": 26
} |
767 | diff --git a/ext/standard/file.h b/ext/standard/file.h
index 3a9cf1435b143..f8faebd028293 100644
--- a/ext/standard/file.h
+++ b/ext/standard/file.h
@@ -36,7 +36,6 @@ PHPAPI PHP_FUNCTION(fpassthru);
PHP_MINIT_FUNCTION(user_streams);
-PHPAPI int php_le_stream_context(void);
PHPAPI zend_result php_copy_file(const char *src, const char *dest);
PHPAPI zend_result php_copy_file_ex(const char *src, const char *dest, int src_flags);
PHPAPI zend_result php_copy_file_ctx(const char *src, const char *dest, int src_flags, php_stream_context *ctx);
diff --git a/main/php_streams.h b/main/php_streams.h
index 80cb96951ee14..adc0811c92c23 100644
--- a/main/php_streams.h
+++ b/main/php_streams.h
@@ -285,6 +285,10 @@ END_EXTERN_C()
#define php_stream_from_res_no_verify(xstr, pzval) (xstr) = (php_stream*)zend_fetch_resource2((res), "stream", php_file_le_stream(), php_file_le_pstream())
#define php_stream_from_zval_no_verify(xstr, pzval) (xstr) = (php_stream*)zend_fetch_resource2_ex((pzval), "stream", php_file_le_stream(), php_file_le_pstream())
+static zend_always_inline php_stream* php_stream_from_zval_no_verify_no_error(zval *zval) {
+ return (php_stream*)zend_fetch_resource2_ex(zval, NULL, php_file_le_stream(), php_file_le_pstream());
+}
+
BEGIN_EXTERN_C()
static zend_always_inline bool php_stream_zend_parse_arg_into_stream(zval *arg, php_stream **destination_stream_ptr, bool check_null)
diff --git a/main/streams/php_stream_context.h b/main/streams/php_stream_context.h
index d4ebe29bc162e..a5325a94642c9 100644
--- a/main/streams/php_stream_context.h
+++ b/main/streams/php_stream_context.h
@@ -25,14 +25,17 @@ typedef void (*php_stream_notification_func)(php_stream_context *context,
#define PHP_STREAM_NOTIFIER_PROGRESS 1
+/* TODO: Remove dependence on ext/standard/file.h for the default context global */
+#define php_stream_context_get_default(without_context) \
+ (without_context) ? NULL : FG(default_context) ? FG(default_context) : \
+ (FG(default_context) = php_stream_context_alloc())
+
/* Attempt to fetch context from the zval passed,
If no context was passed, use the default context
The default context has not yet been created, do it now. */
#define php_stream_context_from_zval(zcontext, nocontext) ( \
(zcontext) ? zend_fetch_resource_ex(zcontext, "Stream-Context", php_le_stream_context()) : \
- (nocontext) ? NULL : \
- FG(default_context) ? FG(default_context) : \
- (FG(default_context) = php_stream_context_alloc()) )
+ php_stream_context_get_default(nocontext))
#define php_stream_context_to_zval(context, zval) { ZVAL_RES(zval, (context)->res); GC_ADDREF((context)->res); }
@@ -53,6 +56,7 @@ struct _php_stream_context {
};
BEGIN_EXTERN_C()
+PHPAPI int php_le_stream_context(void);
PHPAPI void php_stream_context_free(php_stream_context *context);
PHPAPI php_stream_context *php_stream_context_alloc(void);
PHPAPI zval *php_stream_context_get_option(php_stream_context *context,
| diff --git a/ext/standard/file.h b/ext/standard/file.h
index 3a9cf1435b143..f8faebd028293 100644
--- a/ext/standard/file.h
+++ b/ext/standard/file.h
@@ -36,7 +36,6 @@ PHPAPI PHP_FUNCTION(fpassthru);
PHP_MINIT_FUNCTION(user_streams);
-PHPAPI int php_le_stream_context(void);
PHPAPI zend_result php_copy_file(const char *src, const char *dest);
PHPAPI zend_result php_copy_file_ex(const char *src, const char *dest, int src_flags);
PHPAPI zend_result php_copy_file_ctx(const char *src, const char *dest, int src_flags, php_stream_context *ctx);
diff --git a/main/php_streams.h b/main/php_streams.h
index 80cb96951ee14..adc0811c92c23 100644
--- a/main/php_streams.h
+++ b/main/php_streams.h
@@ -285,6 +285,10 @@ END_EXTERN_C()
#define php_stream_from_res_no_verify(xstr, pzval) (xstr) = (php_stream*)zend_fetch_resource2((res), "stream", php_file_le_stream(), php_file_le_pstream())
#define php_stream_from_zval_no_verify(xstr, pzval) (xstr) = (php_stream*)zend_fetch_resource2_ex((pzval), "stream", php_file_le_stream(), php_file_le_pstream())
+static zend_always_inline php_stream* php_stream_from_zval_no_verify_no_error(zval *zval) {
+ return (php_stream*)zend_fetch_resource2_ex(zval, NULL, php_file_le_stream(), php_file_le_pstream());
+}
static zend_always_inline bool php_stream_zend_parse_arg_into_stream(zval *arg, php_stream **destination_stream_ptr, bool check_null)
diff --git a/main/streams/php_stream_context.h b/main/streams/php_stream_context.h
index d4ebe29bc162e..a5325a94642c9 100644
--- a/main/streams/php_stream_context.h
+++ b/main/streams/php_stream_context.h
@@ -25,14 +25,17 @@ typedef void (*php_stream_notification_func)(php_stream_context *context,
#define PHP_STREAM_NOTIFIER_PROGRESS 1
+/* TODO: Remove dependence on ext/standard/file.h for the default context global */
+#define php_stream_context_get_default(without_context) \
+ (without_context) ? NULL : FG(default_context) ? FG(default_context) : \
+ (FG(default_context) = php_stream_context_alloc())
/* Attempt to fetch context from the zval passed,
If no context was passed, use the default context
The default context has not yet been created, do it now. */
#define php_stream_context_from_zval(zcontext, nocontext) ( \
(zcontext) ? zend_fetch_resource_ex(zcontext, "Stream-Context", php_le_stream_context()) : \
- (nocontext) ? NULL : \
- FG(default_context) ? FG(default_context) : \
- (FG(default_context) = php_stream_context_alloc()) )
#define php_stream_context_to_zval(context, zval) { ZVAL_RES(zval, (context)->res); GC_ADDREF((context)->res); }
@@ -53,6 +56,7 @@ struct _php_stream_context {
};
+PHPAPI int php_le_stream_context(void);
PHPAPI void php_stream_context_free(php_stream_context *context);
PHPAPI php_stream_context *php_stream_context_alloc(void);
PHPAPI zval *php_stream_context_get_option(php_stream_context *context, | [
"+\t\tphp_stream_context_get_default(nocontext))"
] | [
48
] | {
"additions": 11,
"author": "Girgias",
"deletions": 4,
"html_url": "https://github.com/php/php-src/pull/18097",
"issue_id": 18097,
"merged_at": "2025-03-30T18:35:05Z",
"omission_probability": 0.1,
"pr_number": 18097,
"repo": "php/php-src",
"title": "main/streams: Move definitions to reduce ext/standard dependency and add new API",
"total_changes": 15
} |
768 | diff --git a/ext/spl/spl_fixedarray.c b/ext/spl/spl_fixedarray.c
index 4efce87b1a9cd..3b9c9e2d22785 100644
--- a/ext/spl/spl_fixedarray.c
+++ b/ext/spl/spl_fixedarray.c
@@ -730,22 +730,29 @@ PHP_METHOD(SplFixedArray, fromArray)
zend_ulong num_index, max_index = 0;
zend_long tmp;
- ZEND_HASH_FOREACH_KEY(Z_ARRVAL_P(data), num_index, str_index) {
- if (str_index != NULL || (zend_long)num_index < 0) {
- zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "array must contain only positive integer keys");
+ if (HT_IS_PACKED(Z_ARRVAL_P(data))) {
+ /* If there are no holes, then nNumUsed is the number of elements.
+ * If there are holes, then nNumUsed is the index of the last element. */
+ tmp = Z_ARRVAL_P(data)->nNumUsed;
+ } else {
+ ZEND_HASH_MAP_FOREACH_KEY(Z_ARRVAL_P(data), num_index, str_index) {
+ if (str_index != NULL || (zend_long)num_index < 0) {
+ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "array must contain only positive integer keys");
+ RETURN_THROWS();
+ }
+
+ if (num_index > max_index) {
+ max_index = num_index;
+ }
+ } ZEND_HASH_FOREACH_END();
+
+ tmp = max_index + 1;
+ if (tmp <= 0) {
+ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "integer overflow detected");
RETURN_THROWS();
}
-
- if (num_index > max_index) {
- max_index = num_index;
- }
- } ZEND_HASH_FOREACH_END();
-
- tmp = max_index + 1;
- if (tmp <= 0) {
- zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "integer overflow detected");
- RETURN_THROWS();
}
+
spl_fixedarray_init(&array, tmp);
ZEND_HASH_FOREACH_NUM_KEY_VAL(Z_ARRVAL_P(data), num_index, element) {
| diff --git a/ext/spl/spl_fixedarray.c b/ext/spl/spl_fixedarray.c
index 4efce87b1a9cd..3b9c9e2d22785 100644
--- a/ext/spl/spl_fixedarray.c
+++ b/ext/spl/spl_fixedarray.c
@@ -730,22 +730,29 @@ PHP_METHOD(SplFixedArray, fromArray)
zend_ulong num_index, max_index = 0;
zend_long tmp;
- if (str_index != NULL || (zend_long)num_index < 0) {
- zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "array must contain only positive integer keys");
+ if (HT_IS_PACKED(Z_ARRVAL_P(data))) {
+ /* If there are no holes, then nNumUsed is the number of elements.
+ * If there are holes, then nNumUsed is the index of the last element. */
+ tmp = Z_ARRVAL_P(data)->nNumUsed;
+ } else {
+ ZEND_HASH_MAP_FOREACH_KEY(Z_ARRVAL_P(data), num_index, str_index) {
+ if (str_index != NULL || (zend_long)num_index < 0) {
+ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "array must contain only positive integer keys");
+ if (num_index > max_index) {
+ max_index = num_index;
+ } ZEND_HASH_FOREACH_END();
+ tmp = max_index + 1;
+ if (tmp <= 0) {
+ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "integer overflow detected");
RETURN_THROWS();
}
- if (num_index > max_index) {
- max_index = num_index;
- }
- } ZEND_HASH_FOREACH_END();
- tmp = max_index + 1;
- if (tmp <= 0) {
- zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "integer overflow detected");
- RETURN_THROWS();
}
spl_fixedarray_init(&array, tmp);
ZEND_HASH_FOREACH_NUM_KEY_VAL(Z_ARRVAL_P(data), num_index, element) { | [
"-\t\tZEND_HASH_FOREACH_KEY(Z_ARRVAL_P(data), num_index, str_index) {",
"+\t\t\t\t\tRETURN_THROWS();"
] | [
8,
19
] | {
"additions": 20,
"author": "nielsdos",
"deletions": 13,
"html_url": "https://github.com/php/php-src/pull/18196",
"issue_id": 18196,
"merged_at": "2025-03-30T18:07:49Z",
"omission_probability": 0.1,
"pr_number": 18196,
"repo": "php/php-src",
"title": "Optimize SplFixedArray::fromArray() for packed arrays",
"total_changes": 33
} |
769 | diff --git a/ext/standard/string.c b/ext/standard/string.c
index b15a24a098faa..1e20791eb61ce 100644
--- a/ext/standard/string.c
+++ b/ext/standard/string.c
@@ -1273,10 +1273,10 @@ PHP_FUNCTION(str_increment)
ZSTR_VAL(tmp)[0] = ZSTR_VAL(incremented)[0];
break;
}
- zend_string_release_ex(incremented, /* persistent */ false);
- RETURN_STR(tmp);
+ zend_string_efree(incremented);
+ RETURN_NEW_STR(tmp);
}
- RETURN_STR(incremented);
+ RETURN_NEW_STR(incremented);
}
@@ -1323,17 +1323,17 @@ PHP_FUNCTION(str_decrement)
if (UNEXPECTED(carry || (ZSTR_VAL(decremented)[0] == '0' && ZSTR_LEN(decremented) > 1))) {
if (ZSTR_LEN(decremented) == 1) {
- zend_string_release_ex(decremented, /* persistent */ false);
+ zend_string_efree(decremented);
zend_argument_value_error(1, "\"%s\" is out of decrement range", ZSTR_VAL(str));
RETURN_THROWS();
}
zend_string *tmp = zend_string_alloc(ZSTR_LEN(decremented) - 1, 0);
memcpy(ZSTR_VAL(tmp), ZSTR_VAL(decremented) + 1, ZSTR_LEN(decremented) - 1);
ZSTR_VAL(tmp)[ZSTR_LEN(decremented) - 1] = '\0';
- zend_string_release_ex(decremented, /* persistent */ false);
- RETURN_STR(tmp);
+ zend_string_efree(decremented);
+ RETURN_NEW_STR(tmp);
}
- RETURN_STR(decremented);
+ RETURN_NEW_STR(decremented);
}
#if defined(PHP_WIN32)
| diff --git a/ext/standard/string.c b/ext/standard/string.c
index b15a24a098faa..1e20791eb61ce 100644
--- a/ext/standard/string.c
+++ b/ext/standard/string.c
@@ -1273,10 +1273,10 @@ PHP_FUNCTION(str_increment)
ZSTR_VAL(tmp)[0] = ZSTR_VAL(incremented)[0];
break;
- zend_string_release_ex(incremented, /* persistent */ false);
- RETURN_STR(incremented);
+ RETURN_NEW_STR(incremented);
@@ -1323,17 +1323,17 @@ PHP_FUNCTION(str_decrement)
if (UNEXPECTED(carry || (ZSTR_VAL(decremented)[0] == '0' && ZSTR_LEN(decremented) > 1))) {
if (ZSTR_LEN(decremented) == 1) {
- zend_string_release_ex(decremented, /* persistent */ false);
+ zend_string_efree(decremented);
zend_argument_value_error(1, "\"%s\" is out of decrement range", ZSTR_VAL(str));
RETURN_THROWS();
zend_string *tmp = zend_string_alloc(ZSTR_LEN(decremented) - 1, 0);
memcpy(ZSTR_VAL(tmp), ZSTR_VAL(decremented) + 1, ZSTR_LEN(decremented) - 1);
ZSTR_VAL(tmp)[ZSTR_LEN(decremented) - 1] = '\0';
- zend_string_release_ex(decremented, /* persistent */ false);
+ zend_string_efree(decremented);
- RETURN_STR(decremented);
+ RETURN_NEW_STR(decremented);
#if defined(PHP_WIN32) | [
"+\t\tzend_string_efree(incremented);"
] | [
10
] | {
"additions": 7,
"author": "nielsdos",
"deletions": 7,
"html_url": "https://github.com/php/php-src/pull/18193",
"issue_id": 18193,
"merged_at": "2025-03-30T16:09:22Z",
"omission_probability": 0.1,
"pr_number": 18193,
"repo": "php/php-src",
"title": "Micro-optimizations to str_increment() and str_decrement()",
"total_changes": 14
} |
770 | diff --git a/ext/spl/spl_fixedarray.c b/ext/spl/spl_fixedarray.c
index b919501c0dd25..53ae39078ffc2 100644
--- a/ext/spl/spl_fixedarray.c
+++ b/ext/spl/spl_fixedarray.c
@@ -872,18 +872,6 @@ PHP_METHOD(SplFixedArray, getIterator)
zend_create_internal_iterator_zval(return_value, ZEND_THIS);
}
-PHP_METHOD(SplFixedArray, jsonSerialize)
-{
- ZEND_PARSE_PARAMETERS_NONE();
-
- spl_fixedarray_object *intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
- array_init_size(return_value, intern->array.size);
- for (zend_long i = 0; i < intern->array.size; i++) {
- zend_hash_next_index_insert_new(Z_ARR_P(return_value), &intern->array.elements[i]);
- Z_TRY_ADDREF(intern->array.elements[i]);
- }
-}
-
static void spl_fixedarray_it_dtor(zend_object_iterator *iter)
{
zval_ptr_dtor(&iter->data);
diff --git a/ext/spl/spl_fixedarray.stub.php b/ext/spl/spl_fixedarray.stub.php
index a5a239ab4d69c..aa8aa5dbed188 100644
--- a/ext/spl/spl_fixedarray.stub.php
+++ b/ext/spl/spl_fixedarray.stub.php
@@ -55,5 +55,8 @@ public function offsetUnset($index): void {}
public function getIterator(): Iterator {}
+ /**
+ * @implementation-alias SplFixedArray::toArray
+ */
public function jsonSerialize(): array {}
}
diff --git a/ext/spl/spl_fixedarray_arginfo.h b/ext/spl/spl_fixedarray_arginfo.h
index 5d83183d91b81..c2ff9a77ac40f 100644
--- a/ext/spl/spl_fixedarray_arginfo.h
+++ b/ext/spl/spl_fixedarray_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: c01c9337e58601ff9e6c85072a62f68cc7fec9ba */
+ * Stub hash: 0c838fed60b29671fe04e63315ab662d8cb16f0c */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_SplFixedArray___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, size, IS_LONG, 0, "0")
@@ -68,7 +68,6 @@ ZEND_METHOD(SplFixedArray, offsetGet);
ZEND_METHOD(SplFixedArray, offsetSet);
ZEND_METHOD(SplFixedArray, offsetUnset);
ZEND_METHOD(SplFixedArray, getIterator);
-ZEND_METHOD(SplFixedArray, jsonSerialize);
static const zend_function_entry class_SplFixedArray_methods[] = {
ZEND_ME(SplFixedArray, __construct, arginfo_class_SplFixedArray___construct, ZEND_ACC_PUBLIC)
@@ -85,7 +84,7 @@ static const zend_function_entry class_SplFixedArray_methods[] = {
ZEND_ME(SplFixedArray, offsetSet, arginfo_class_SplFixedArray_offsetSet, ZEND_ACC_PUBLIC)
ZEND_ME(SplFixedArray, offsetUnset, arginfo_class_SplFixedArray_offsetUnset, ZEND_ACC_PUBLIC)
ZEND_ME(SplFixedArray, getIterator, arginfo_class_SplFixedArray_getIterator, ZEND_ACC_PUBLIC)
- ZEND_ME(SplFixedArray, jsonSerialize, arginfo_class_SplFixedArray_jsonSerialize, ZEND_ACC_PUBLIC)
+ ZEND_RAW_FENTRY("jsonSerialize", zim_SplFixedArray_toArray, arginfo_class_SplFixedArray_jsonSerialize, ZEND_ACC_PUBLIC, NULL, NULL)
ZEND_FE_END
};
| diff --git a/ext/spl/spl_fixedarray.c b/ext/spl/spl_fixedarray.c
index b919501c0dd25..53ae39078ffc2 100644
--- a/ext/spl/spl_fixedarray.c
+++ b/ext/spl/spl_fixedarray.c
@@ -872,18 +872,6 @@ PHP_METHOD(SplFixedArray, getIterator)
zend_create_internal_iterator_zval(return_value, ZEND_THIS);
-PHP_METHOD(SplFixedArray, jsonSerialize)
-{
- ZEND_PARSE_PARAMETERS_NONE();
- spl_fixedarray_object *intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
- array_init_size(return_value, intern->array.size);
- for (zend_long i = 0; i < intern->array.size; i++) {
- zend_hash_next_index_insert_new(Z_ARR_P(return_value), &intern->array.elements[i]);
- Z_TRY_ADDREF(intern->array.elements[i]);
- }
-}
static void spl_fixedarray_it_dtor(zend_object_iterator *iter)
{
zval_ptr_dtor(&iter->data);
diff --git a/ext/spl/spl_fixedarray.stub.php b/ext/spl/spl_fixedarray.stub.php
index a5a239ab4d69c..aa8aa5dbed188 100644
--- a/ext/spl/spl_fixedarray.stub.php
+++ b/ext/spl/spl_fixedarray.stub.php
@@ -55,5 +55,8 @@ public function offsetUnset($index): void {}
public function getIterator(): Iterator {}
+ /**
+ */
public function jsonSerialize(): array {}
diff --git a/ext/spl/spl_fixedarray_arginfo.h b/ext/spl/spl_fixedarray_arginfo.h
index 5d83183d91b81..c2ff9a77ac40f 100644
--- a/ext/spl/spl_fixedarray_arginfo.h
+++ b/ext/spl/spl_fixedarray_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: c01c9337e58601ff9e6c85072a62f68cc7fec9ba */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_SplFixedArray___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, size, IS_LONG, 0, "0")
@@ -68,7 +68,6 @@ ZEND_METHOD(SplFixedArray, offsetGet);
ZEND_METHOD(SplFixedArray, offsetSet);
ZEND_METHOD(SplFixedArray, offsetUnset);
ZEND_METHOD(SplFixedArray, getIterator);
-ZEND_METHOD(SplFixedArray, jsonSerialize);
static const zend_function_entry class_SplFixedArray_methods[] = {
ZEND_ME(SplFixedArray, __construct, arginfo_class_SplFixedArray___construct, ZEND_ACC_PUBLIC)
@@ -85,7 +84,7 @@ static const zend_function_entry class_SplFixedArray_methods[] = {
ZEND_ME(SplFixedArray, offsetSet, arginfo_class_SplFixedArray_offsetSet, ZEND_ACC_PUBLIC)
ZEND_ME(SplFixedArray, offsetUnset, arginfo_class_SplFixedArray_offsetUnset, ZEND_ACC_PUBLIC)
ZEND_ME(SplFixedArray, getIterator, arginfo_class_SplFixedArray_getIterator, ZEND_ACC_PUBLIC)
- ZEND_ME(SplFixedArray, jsonSerialize, arginfo_class_SplFixedArray_jsonSerialize, ZEND_ACC_PUBLIC)
ZEND_FE_END
}; | [
"+ * @implementation-alias SplFixedArray::toArray",
"+ * Stub hash: 0c838fed60b29671fe04e63315ab662d8cb16f0c */",
"+\tZEND_RAW_FENTRY(\"jsonSerialize\", zim_SplFixedArray_toArray, arginfo_class_SplFixedArray_jsonSerialize, ZEND_ACC_PUBLIC, NULL, NULL)"
] | [
32,
43,
60
] | {
"additions": 5,
"author": "nielsdos",
"deletions": 15,
"html_url": "https://github.com/php/php-src/pull/18191",
"issue_id": 18191,
"merged_at": "2025-03-30T16:09:12Z",
"omission_probability": 0.1,
"pr_number": 18191,
"repo": "php/php-src",
"title": "Make SplFixedArray::jsonSerialize() an implementation alias of SplFixedArray::toArray()",
"total_changes": 20
} |
771 | diff --git a/ext/spl/spl_fixedarray.c b/ext/spl/spl_fixedarray.c
index b919501c0dd25..ab81563caba9f 100644
--- a/ext/spl/spl_fixedarray.c
+++ b/ext/spl/spl_fixedarray.c
@@ -691,11 +691,16 @@ PHP_METHOD(SplFixedArray, toArray)
intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
if (!spl_fixedarray_empty(&intern->array)) {
- array_init(return_value);
- for (zend_long i = 0; i < intern->array.size; i++) {
- zend_hash_index_update(Z_ARRVAL_P(return_value), i, &intern->array.elements[i]);
- Z_TRY_ADDREF(intern->array.elements[i]);
- }
+ array_init_size(return_value, intern->array.size);
+ HashTable *ht = Z_ARRVAL_P(return_value);
+ zend_hash_real_init_packed(ht);
+
+ ZEND_HASH_FILL_PACKED(ht) {
+ for (zend_long i = 0; i < intern->array.size; i++) {
+ ZEND_HASH_FILL_ADD(&intern->array.elements[i]);
+ Z_TRY_ADDREF(intern->array.elements[i]);
+ }
+ } ZEND_HASH_FILL_END();
} else {
RETURN_EMPTY_ARRAY();
}
| diff --git a/ext/spl/spl_fixedarray.c b/ext/spl/spl_fixedarray.c
index b919501c0dd25..ab81563caba9f 100644
--- a/ext/spl/spl_fixedarray.c
+++ b/ext/spl/spl_fixedarray.c
@@ -691,11 +691,16 @@ PHP_METHOD(SplFixedArray, toArray)
intern = Z_SPLFIXEDARRAY_P(ZEND_THIS);
if (!spl_fixedarray_empty(&intern->array)) {
- array_init(return_value);
- for (zend_long i = 0; i < intern->array.size; i++) {
- zend_hash_index_update(Z_ARRVAL_P(return_value), i, &intern->array.elements[i]);
- Z_TRY_ADDREF(intern->array.elements[i]);
- }
+ array_init_size(return_value, intern->array.size);
+ HashTable *ht = Z_ARRVAL_P(return_value);
+ zend_hash_real_init_packed(ht);
+ ZEND_HASH_FILL_PACKED(ht) {
+ for (zend_long i = 0; i < intern->array.size; i++) {
+ ZEND_HASH_FILL_ADD(&intern->array.elements[i]);
+ Z_TRY_ADDREF(intern->array.elements[i]);
+ }
+ } ZEND_HASH_FILL_END();
} else {
RETURN_EMPTY_ARRAY();
} | [
"+"
] | [
16
] | {
"additions": 10,
"author": "nielsdos",
"deletions": 5,
"html_url": "https://github.com/php/php-src/pull/18190",
"issue_id": 18190,
"merged_at": "2025-03-30T16:09:02Z",
"omission_probability": 0.1,
"pr_number": 18190,
"repo": "php/php-src",
"title": "Optimize SplFixedArray::toArray()",
"total_changes": 15
} |
772 | diff --git a/ext/spl/spl_fixedarray.c b/ext/spl/spl_fixedarray.c
index b919501c0dd25..fa846e48eee03 100644
--- a/ext/spl/spl_fixedarray.c
+++ b/ext/spl/spl_fixedarray.c
@@ -324,14 +324,14 @@ static zend_object *spl_fixedarray_object_clone(zend_object *old_object)
return new_object;
}
-static zend_long spl_offset_convert_to_long(zval *offset) /* {{{ */
+static zend_never_inline zend_ulong spl_offset_convert_to_ulong_slow(const zval *offset) /* {{{ */
{
try_again:
switch (Z_TYPE_P(offset)) {
case IS_STRING: {
zend_ulong index;
if (ZEND_HANDLE_NUMERIC(Z_STR_P(offset), index)) {
- return (zend_long) index;
+ return index;
}
break;
}
@@ -356,10 +356,22 @@ static zend_long spl_offset_convert_to_long(zval *offset) /* {{{ */
return 0;
}
-static zval *spl_fixedarray_object_read_dimension_helper(spl_fixedarray_object *intern, zval *offset)
+/* Returned index is an unsigned number such that we don't have to do a negative check.
+ * Negative numbers will be mapped at indices larger than ZEND_ULONG_MAX,
+ * which is beyond the maximum length. */
+static zend_always_inline zend_ulong spl_offset_convert_to_ulong(const zval *offset)
{
- zend_long index;
+ if (EXPECTED(Z_TYPE_P(offset) == IS_LONG)) {
+ /* Allow skipping exception check at call-site. */
+ ZEND_ASSERT(!EG(exception));
+ return Z_LVAL_P(offset);
+ } else {
+ return spl_offset_convert_to_ulong_slow(offset);
+ }
+}
+static zval *spl_fixedarray_object_read_dimension_helper(spl_fixedarray_object *intern, zval *offset)
+{
/* we have to return NULL on error here to avoid memleak because of
* ZE duplicating uninitialized_zval_ptr */
if (!offset) {
@@ -367,12 +379,12 @@ static zval *spl_fixedarray_object_read_dimension_helper(spl_fixedarray_object *
return NULL;
}
- index = spl_offset_convert_to_long(offset);
- if (EG(exception)) {
+ zend_ulong index = spl_offset_convert_to_ulong(offset);
+ if (UNEXPECTED(EG(exception))) {
return NULL;
}
- if (index < 0 || index >= intern->array.size) {
+ if (UNEXPECTED(index >= intern->array.size)) {
zend_throw_exception(spl_ce_OutOfBoundsException, "Index invalid or out of range", 0);
return NULL;
} else {
@@ -407,22 +419,19 @@ static zval *spl_fixedarray_object_read_dimension(zend_object *object, zval *off
static void spl_fixedarray_object_write_dimension_helper(spl_fixedarray_object *intern, zval *offset, zval *value)
{
- zend_long index;
-
if (!offset) {
/* '$array[] = value' syntax is not supported */
zend_throw_error(NULL, "[] operator not supported for SplFixedArray");
return;
}
- index = spl_offset_convert_to_long(offset);
- if (EG(exception)) {
+ zend_ulong index = spl_offset_convert_to_ulong(offset);
+ if (UNEXPECTED(EG(exception))) {
return;
}
- if (index < 0 || index >= intern->array.size) {
+ if (UNEXPECTED(index >= intern->array.size)) {
zend_throw_exception(spl_ce_OutOfBoundsException, "Index invalid or out of range", 0);
- return;
} else {
/* Fix #81429 */
zval *ptr = &(intern->array.elements[index]);
@@ -452,16 +461,13 @@ static void spl_fixedarray_object_write_dimension(zend_object *object, zval *off
static void spl_fixedarray_object_unset_dimension_helper(spl_fixedarray_object *intern, zval *offset)
{
- zend_long index;
-
- index = spl_offset_convert_to_long(offset);
- if (EG(exception)) {
+ zend_ulong index = spl_offset_convert_to_ulong(offset);
+ if (UNEXPECTED(EG(exception))) {
return;
}
- if (index < 0 || index >= intern->array.size) {
+ if (UNEXPECTED(index >= intern->array.size)) {
zend_throw_exception(spl_ce_OutOfBoundsException, "Index invalid or out of range", 0);
- return;
} else {
zval garbage;
ZVAL_COPY_VALUE(&garbage, &intern->array.elements[index]);
@@ -483,14 +489,12 @@ static void spl_fixedarray_object_unset_dimension(zend_object *object, zval *off
static bool spl_fixedarray_object_has_dimension_helper(spl_fixedarray_object *intern, zval *offset, bool check_empty)
{
- zend_long index;
-
- index = spl_offset_convert_to_long(offset);
- if (EG(exception)) {
+ zend_ulong index = spl_offset_convert_to_ulong(offset);
+ if (UNEXPECTED(EG(exception))) {
return false;
}
- if (index < 0 || index >= intern->array.size) {
+ if (index >= intern->array.size) {
return false;
}
| diff --git a/ext/spl/spl_fixedarray.c b/ext/spl/spl_fixedarray.c
index b919501c0dd25..fa846e48eee03 100644
--- a/ext/spl/spl_fixedarray.c
+++ b/ext/spl/spl_fixedarray.c
@@ -324,14 +324,14 @@ static zend_object *spl_fixedarray_object_clone(zend_object *old_object)
return new_object;
+static zend_never_inline zend_ulong spl_offset_convert_to_ulong_slow(const zval *offset) /* {{{ */
try_again:
switch (Z_TYPE_P(offset)) {
case IS_STRING: {
zend_ulong index;
if (ZEND_HANDLE_NUMERIC(Z_STR_P(offset), index)) {
- return (zend_long) index;
+ return index;
}
break;
}
@@ -356,10 +356,22 @@ static zend_long spl_offset_convert_to_long(zval *offset) /* {{{ */
return 0;
-static zval *spl_fixedarray_object_read_dimension_helper(spl_fixedarray_object *intern, zval *offset)
+/* Returned index is an unsigned number such that we don't have to do a negative check.
+ * Negative numbers will be mapped at indices larger than ZEND_ULONG_MAX,
+ * which is beyond the maximum length. */
+static zend_always_inline zend_ulong spl_offset_convert_to_ulong(const zval *offset)
+ if (EXPECTED(Z_TYPE_P(offset) == IS_LONG)) {
+ /* Allow skipping exception check at call-site. */
+ return Z_LVAL_P(offset);
+ } else {
+ return spl_offset_convert_to_ulong_slow(offset);
+ }
+}
+static zval *spl_fixedarray_object_read_dimension_helper(spl_fixedarray_object *intern, zval *offset)
+{
/* we have to return NULL on error here to avoid memleak because of
* ZE duplicating uninitialized_zval_ptr */
@@ -367,12 +379,12 @@ static zval *spl_fixedarray_object_read_dimension_helper(spl_fixedarray_object *
@@ -407,22 +419,19 @@ static zval *spl_fixedarray_object_read_dimension(zend_object *object, zval *off
static void spl_fixedarray_object_write_dimension_helper(spl_fixedarray_object *intern, zval *offset, zval *value)
/* '$array[] = value' syntax is not supported */
zend_throw_error(NULL, "[] operator not supported for SplFixedArray");
/* Fix #81429 */
zval *ptr = &(intern->array.elements[index]);
@@ -452,16 +461,13 @@ static void spl_fixedarray_object_write_dimension(zend_object *object, zval *off
static void spl_fixedarray_object_unset_dimension_helper(spl_fixedarray_object *intern, zval *offset)
zval garbage;
ZVAL_COPY_VALUE(&garbage, &intern->array.elements[index]);
@@ -483,14 +489,12 @@ static void spl_fixedarray_object_unset_dimension(zend_object *object, zval *off
static bool spl_fixedarray_object_has_dimension_helper(spl_fixedarray_object *intern, zval *offset, bool check_empty)
+ if (index >= intern->array.size) { | [
"-static zend_long spl_offset_convert_to_long(zval *offset) /* {{{ */",
"+\t\tZEND_ASSERT(!EG(exception));"
] | [
8,
34
] | {
"additions": 28,
"author": "nielsdos",
"deletions": 24,
"html_url": "https://github.com/php/php-src/pull/18184",
"issue_id": 18184,
"merged_at": "2025-03-30T11:16:34Z",
"omission_probability": 0.1,
"pr_number": 18184,
"repo": "php/php-src",
"title": "Optimize SplFixedArray dimension performance",
"total_changes": 52
} |
773 | diff --git a/ext/dom/namespace_compat.c b/ext/dom/namespace_compat.c
index 7a3bd68b0111a..ee32ec39dbeb3 100644
--- a/ext/dom/namespace_compat.c
+++ b/ext/dom/namespace_compat.c
@@ -180,7 +180,7 @@ PHP_DOM_EXPORT xmlNsPtr php_dom_libxml_ns_mapper_get_ns_raw_strings_nullsafe(php
return php_dom_libxml_ns_mapper_get_ns_raw_strings(mapper, prefix, uri);
}
-static xmlNsPtr php_dom_libxml_ns_mapper_store_and_normalize_parsed_ns(php_dom_libxml_ns_mapper *mapper, xmlNsPtr ns)
+static void php_dom_libxml_ns_mapper_store_and_normalize_parsed_ns(php_dom_libxml_ns_mapper *mapper, xmlNsPtr ns)
{
ZEND_ASSERT(ns != NULL);
@@ -198,16 +198,9 @@ static xmlNsPtr php_dom_libxml_ns_mapper_store_and_normalize_parsed_ns(php_dom_l
prefix_len = xmlStrlen(ns->prefix);
}
- zval *zv = zend_hash_str_find_ptr(prefix_map, prefix, prefix_len);
- if (zv != NULL) {
- return Z_PTR_P(zv);
- }
-
zval new_zv;
DOM_Z_UNOWNED(&new_zv, ns);
- zend_hash_str_add_new(prefix_map, prefix, prefix_len, &new_zv);
-
- return ns;
+ zend_hash_str_add(prefix_map, prefix, prefix_len, &new_zv);
}
typedef struct {
| diff --git a/ext/dom/namespace_compat.c b/ext/dom/namespace_compat.c
index 7a3bd68b0111a..ee32ec39dbeb3 100644
--- a/ext/dom/namespace_compat.c
+++ b/ext/dom/namespace_compat.c
@@ -180,7 +180,7 @@ PHP_DOM_EXPORT xmlNsPtr php_dom_libxml_ns_mapper_get_ns_raw_strings_nullsafe(php
return php_dom_libxml_ns_mapper_get_ns_raw_strings(mapper, prefix, uri);
-static xmlNsPtr php_dom_libxml_ns_mapper_store_and_normalize_parsed_ns(php_dom_libxml_ns_mapper *mapper, xmlNsPtr ns)
+static void php_dom_libxml_ns_mapper_store_and_normalize_parsed_ns(php_dom_libxml_ns_mapper *mapper, xmlNsPtr ns)
{
ZEND_ASSERT(ns != NULL);
@@ -198,16 +198,9 @@ static xmlNsPtr php_dom_libxml_ns_mapper_store_and_normalize_parsed_ns(php_dom_l
prefix_len = xmlStrlen(ns->prefix);
}
- zval *zv = zend_hash_str_find_ptr(prefix_map, prefix, prefix_len);
- if (zv != NULL) {
- return Z_PTR_P(zv);
- }
zval new_zv;
DOM_Z_UNOWNED(&new_zv, ns);
- zend_hash_str_add_new(prefix_map, prefix, prefix_len, &new_zv);
- return ns;
+ zend_hash_str_add(prefix_map, prefix, prefix_len, &new_zv);
typedef struct { | [] | [] | {
"additions": 2,
"author": "nielsdos",
"deletions": 9,
"html_url": "https://github.com/php/php-src/pull/18182",
"issue_id": 18182,
"merged_at": "2025-03-29T21:46:19Z",
"omission_probability": 0.1,
"pr_number": 18182,
"repo": "php/php-src",
"title": "Remove useless operations in namespace_compat",
"total_changes": 11
} |
774 | diff --git a/ext/standard/array.c b/ext/standard/array.c
index 994e0ad34a8cb..aeaef847dd676 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -6437,7 +6437,6 @@ PHP_FUNCTION(array_reduce)
zval *input;
zval args[2];
zval *operand;
- zval retval;
zend_fcall_info fci;
zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
zval *initial = NULL;
@@ -6450,8 +6449,7 @@ PHP_FUNCTION(array_reduce)
Z_PARAM_ZVAL(initial)
ZEND_PARSE_PARAMETERS_END();
-
- if (ZEND_NUM_ARGS() > 2) {
+ if (initial) {
ZVAL_COPY(return_value, initial);
} else {
ZVAL_NULL(return_value);
@@ -6466,24 +6464,22 @@ PHP_FUNCTION(array_reduce)
return;
}
- fci.retval = &retval;
+ fci.retval = return_value;
fci.param_count = 2;
+ fci.params = args;
ZEND_HASH_FOREACH_VAL(htbl, operand) {
ZVAL_COPY_VALUE(&args[0], return_value);
- ZVAL_COPY(&args[1], operand);
- fci.params = args;
+ ZVAL_COPY_VALUE(&args[1], operand);
- if (zend_call_function(&fci, &fci_cache) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
- zval_ptr_dtor(&args[1]);
- zval_ptr_dtor(&args[0]);
- ZVAL_COPY_VALUE(return_value, &retval);
+ zend_call_function(&fci, &fci_cache);
+ zval_ptr_dtor(&args[0]);
+
+ if (EXPECTED(!Z_ISUNDEF_P(return_value))) {
if (UNEXPECTED(Z_ISREF_P(return_value))) {
zend_unwrap_reference(return_value);
}
} else {
- zval_ptr_dtor(&args[1]);
- zval_ptr_dtor(&args[0]);
RETURN_NULL();
}
} ZEND_HASH_FOREACH_END();
| diff --git a/ext/standard/array.c b/ext/standard/array.c
index 994e0ad34a8cb..aeaef847dd676 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -6437,7 +6437,6 @@ PHP_FUNCTION(array_reduce)
zval *input;
zval args[2];
zval *operand;
- zval retval;
zend_fcall_info fci;
zend_fcall_info_cache fci_cache = empty_fcall_info_cache;
zval *initial = NULL;
@@ -6450,8 +6449,7 @@ PHP_FUNCTION(array_reduce)
Z_PARAM_ZVAL(initial)
ZEND_PARSE_PARAMETERS_END();
-
- if (ZEND_NUM_ARGS() > 2) {
+ if (initial) {
ZVAL_COPY(return_value, initial);
} else {
ZVAL_NULL(return_value);
@@ -6466,24 +6464,22 @@ PHP_FUNCTION(array_reduce)
return;
}
- fci.retval = &retval;
+ fci.retval = return_value;
fci.param_count = 2;
+ fci.params = args;
ZEND_HASH_FOREACH_VAL(htbl, operand) {
ZVAL_COPY_VALUE(&args[0], return_value);
- ZVAL_COPY(&args[1], operand);
- fci.params = args;
+ ZVAL_COPY_VALUE(&args[1], operand);
- if (zend_call_function(&fci, &fci_cache) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
- ZVAL_COPY_VALUE(return_value, &retval);
+ zend_call_function(&fci, &fci_cache);
+ zval_ptr_dtor(&args[0]);
+
+ if (EXPECTED(!Z_ISUNDEF_P(return_value))) {
if (UNEXPECTED(Z_ISREF_P(return_value))) {
zend_unwrap_reference(return_value);
}
} else {
RETURN_NULL();
}
} ZEND_HASH_FOREACH_END(); | [] | [] | {
"additions": 8,
"author": "nielsdos",
"deletions": 12,
"html_url": "https://github.com/php/php-src/pull/18180",
"issue_id": 18180,
"merged_at": "2025-03-29T21:45:58Z",
"omission_probability": 0.1,
"pr_number": 18180,
"repo": "php/php-src",
"title": "Avoid pointless refcounting in array_reduce",
"total_changes": 20
} |
775 | diff --git a/ext/standard/array.c b/ext/standard/array.c
index 8462492651310..d26e238180262 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -6509,6 +6509,22 @@ PHP_FUNCTION(array_reduce)
}
/* }}} */
+/* Consumes `zv` */
+static bool php_is_true(zval *zv)
+{
+ switch (Z_TYPE_P(zv)) {
+ case IS_TRUE:
+ return true;
+ case IS_FALSE:
+ return false;
+ default: {
+ bool rv = zend_is_true(zv);
+ zval_ptr_dtor(zv);
+ return rv;
+ }
+ }
+}
+
/* {{{ Filters elements from the array via the callback. */
PHP_FUNCTION(array_filter)
{
@@ -6571,9 +6587,7 @@ PHP_FUNCTION(array_filter)
RETURN_THROWS();
}
- bool retval_true = zend_is_true(&retval);
- zval_ptr_dtor(&retval);
- if (!retval_true) {
+ if (!php_is_true(&retval)) {
continue;
}
} else if (!zend_is_true(operand)) {
@@ -6597,7 +6611,7 @@ enum php_array_find_result {
PHP_ARRAY_FIND_SOME = 1,
};
-static enum php_array_find_result php_array_find(const HashTable *array, zend_fcall_info fci, zend_fcall_info_cache fci_cache, zval *result_key, zval *result_value, bool negate_condition)
+static enum php_array_find_result php_array_find(const HashTable *array, zend_fcall_info fci, zend_fcall_info_cache *fci_cache, zval *result_key, zval *result_value, bool negate_condition)
{
zend_ulong num_key;
zend_string *str_key;
@@ -6620,25 +6634,22 @@ static enum php_array_find_result php_array_find(const HashTable *array, zend_fc
if (!str_key) {
ZVAL_LONG(&args[1], num_key);
} else {
+ /* Allows copying the numeric branch, without this branch, into the iteration code
+ * that checks for the packed array flag. */
+ ZEND_ASSUME(!HT_IS_PACKED(array));
ZVAL_STR(&args[1], str_key);
}
ZVAL_COPY_VALUE(&args[0], operand);
- zend_result result = zend_call_function(&fci, &fci_cache);
+ zend_result result = zend_call_function(&fci, fci_cache);
ZEND_ASSERT(result == SUCCESS);
if (UNEXPECTED(Z_ISUNDEF(retval))) {
return PHP_ARRAY_FIND_EXCEPTION;
}
- bool retval_true = zend_is_true(&retval);
- zval_ptr_dtor(&retval);
-
- /* This negates the condition, if negate_condition is true. Otherwise it does nothing with `retval_true`. */
- retval_true ^= negate_condition;
-
- if (retval_true) {
+ if (php_is_true(&retval) ^ negate_condition) {
if (result_value != NULL) {
ZVAL_COPY_DEREF(result_value, &args[0]);
}
@@ -6667,7 +6678,7 @@ PHP_FUNCTION(array_find)
Z_PARAM_FUNC(fci, fci_cache)
ZEND_PARSE_PARAMETERS_END();
- php_array_find(array, fci, fci_cache, NULL, return_value, false);
+ php_array_find(array, fci, &fci_cache, NULL, return_value, false);
}
/* }}} */
@@ -6683,7 +6694,7 @@ PHP_FUNCTION(array_find_key)
Z_PARAM_FUNC(fci, fci_cache)
ZEND_PARSE_PARAMETERS_END();
- php_array_find(array, fci, fci_cache, return_value, NULL, false);
+ php_array_find(array, fci, &fci_cache, return_value, NULL, false);
}
/* }}} */
@@ -6699,7 +6710,7 @@ PHP_FUNCTION(array_any)
Z_PARAM_FUNC(fci, fci_cache)
ZEND_PARSE_PARAMETERS_END();
- RETURN_BOOL(php_array_find(array, fci, fci_cache, NULL, NULL, false) == PHP_ARRAY_FIND_SOME);
+ RETURN_BOOL(php_array_find(array, fci, &fci_cache, NULL, NULL, false) == PHP_ARRAY_FIND_SOME);
}
/* }}} */
@@ -6715,7 +6726,7 @@ PHP_FUNCTION(array_all)
Z_PARAM_FUNC(fci, fci_cache)
ZEND_PARSE_PARAMETERS_END();
- RETURN_BOOL(php_array_find(array, fci, fci_cache, NULL, NULL, true) == PHP_ARRAY_FIND_NONE);
+ RETURN_BOOL(php_array_find(array, fci, &fci_cache, NULL, NULL, true) == PHP_ARRAY_FIND_NONE);
}
/* }}} */
| diff --git a/ext/standard/array.c b/ext/standard/array.c
index 8462492651310..d26e238180262 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -6509,6 +6509,22 @@ PHP_FUNCTION(array_reduce)
+/* Consumes `zv` */
+static bool php_is_true(zval *zv)
+{
+ case IS_TRUE:
+ return true;
+ case IS_FALSE:
+ return false;
+ default: {
+ bool rv = zend_is_true(zv);
+ zval_ptr_dtor(zv);
+ return rv;
+ }
+ }
+}
/* {{{ Filters elements from the array via the callback. */
PHP_FUNCTION(array_filter)
@@ -6571,9 +6587,7 @@ PHP_FUNCTION(array_filter)
RETURN_THROWS();
- bool retval_true = zend_is_true(&retval);
- zval_ptr_dtor(&retval);
- if (!retval_true) {
+ if (!php_is_true(&retval)) {
continue;
} else if (!zend_is_true(operand)) {
@@ -6597,7 +6611,7 @@ enum php_array_find_result {
PHP_ARRAY_FIND_SOME = 1,
};
-static enum php_array_find_result php_array_find(const HashTable *array, zend_fcall_info fci, zend_fcall_info_cache fci_cache, zval *result_key, zval *result_value, bool negate_condition)
+static enum php_array_find_result php_array_find(const HashTable *array, zend_fcall_info fci, zend_fcall_info_cache *fci_cache, zval *result_key, zval *result_value, bool negate_condition)
zend_ulong num_key;
zend_string *str_key;
@@ -6620,25 +6634,22 @@ static enum php_array_find_result php_array_find(const HashTable *array, zend_fc
if (!str_key) {
ZVAL_LONG(&args[1], num_key);
} else {
+ /* Allows copying the numeric branch, without this branch, into the iteration code
+ * that checks for the packed array flag. */
+ ZEND_ASSUME(!HT_IS_PACKED(array));
ZVAL_STR(&args[1], str_key);
ZVAL_COPY_VALUE(&args[0], operand);
- zend_result result = zend_call_function(&fci, &fci_cache);
+ zend_result result = zend_call_function(&fci, fci_cache);
ZEND_ASSERT(result == SUCCESS);
if (UNEXPECTED(Z_ISUNDEF(retval))) {
return PHP_ARRAY_FIND_EXCEPTION;
- zval_ptr_dtor(&retval);
- /* This negates the condition, if negate_condition is true. Otherwise it does nothing with `retval_true`. */
- retval_true ^= negate_condition;
- if (retval_true) {
+ if (php_is_true(&retval) ^ negate_condition) {
if (result_value != NULL) {
ZVAL_COPY_DEREF(result_value, &args[0]);
@@ -6667,7 +6678,7 @@ PHP_FUNCTION(array_find)
- php_array_find(array, fci, fci_cache, NULL, return_value, false);
+ php_array_find(array, fci, &fci_cache, NULL, return_value, false);
@@ -6683,7 +6694,7 @@ PHP_FUNCTION(array_find_key)
- php_array_find(array, fci, fci_cache, return_value, NULL, false);
+ php_array_find(array, fci, &fci_cache, return_value, NULL, false);
@@ -6699,7 +6710,7 @@ PHP_FUNCTION(array_any)
- RETURN_BOOL(php_array_find(array, fci, fci_cache, NULL, NULL, false) == PHP_ARRAY_FIND_SOME);
+ RETURN_BOOL(php_array_find(array, fci, &fci_cache, NULL, NULL, false) == PHP_ARRAY_FIND_SOME);
@@ -6715,7 +6726,7 @@ PHP_FUNCTION(array_all)
- RETURN_BOOL(php_array_find(array, fci, fci_cache, NULL, NULL, true) == PHP_ARRAY_FIND_NONE);
+ RETURN_BOOL(php_array_find(array, fci, &fci_cache, NULL, NULL, true) == PHP_ARRAY_FIND_NONE); | [
"+\tswitch (Z_TYPE_P(zv)) {",
"+",
"-\t\tbool retval_true = zend_is_true(&retval);"
] | [
11,
23,
67
] | {
"additions": 27,
"author": "nielsdos",
"deletions": 16,
"html_url": "https://github.com/php/php-src/pull/18157",
"issue_id": 18157,
"merged_at": "2025-03-27T22:52:54Z",
"omission_probability": 0.1,
"pr_number": 18157,
"repo": "php/php-src",
"title": "Improve performance of array_find() etc",
"total_changes": 43
} |
776 | diff --git a/UPGRADING.INTERNALS b/UPGRADING.INTERNALS
index 13b5e6a394434..eb5ccd7bd0bd0 100644
--- a/UPGRADING.INTERNALS
+++ b/UPGRADING.INTERNALS
@@ -23,6 +23,8 @@ PHP 8.5 INTERNALS UPGRADE NOTES
for fake closures.
. Added smart_string_append_printf() matching smart_str_append_printf() for
char* instead of zend_string*-based smart strings.
+ . Added php_build_provider() to retrieve the value of PHP_BUILD_PROVIDER at
+ runtime.
========================
2. Build system changes
diff --git a/ext/standard/info.c b/ext/standard/info.c
index 0211265f954a9..952f0f92fe6e2 100644
--- a/ext/standard/info.c
+++ b/ext/standard/info.c
@@ -805,9 +805,9 @@ PHPAPI ZEND_COLD void php_print_info(int flag)
#ifdef PHP_BUILD_SYSTEM
php_info_print_table_row(2, "Build System", PHP_BUILD_SYSTEM);
#endif
-#ifdef PHP_BUILD_PROVIDER
- php_info_print_table_row(2, "Build Provider", PHP_BUILD_PROVIDER);
-#endif
+ if (php_build_provider()) {
+ php_info_print_table_row(2, "Build Provider", php_build_provider());
+ }
#ifdef PHP_BUILD_COMPILER
php_info_print_table_row(2, "Compiler", PHP_BUILD_COMPILER);
#endif
diff --git a/main/main.c b/main/main.c
index 415cb02185e94..50894939782a0 100644
--- a/main/main.c
+++ b/main/main.c
@@ -74,6 +74,7 @@
#include "zend_dtrace.h"
#include "zend_observer.h"
#include "zend_system_id.h"
+#include "zend_smart_string.h"
#include "php_content_types.h"
#include "php_ticks.h"
@@ -99,20 +100,30 @@ PHPAPI size_t core_globals_offset;
const char php_build_date[] = __DATE__ " " __TIME__;
-PHPAPI const char *php_version(void)
+ZEND_ATTRIBUTE_CONST PHPAPI const char *php_version(void)
{
return PHP_VERSION;
}
-PHPAPI unsigned int php_version_id(void)
+ZEND_ATTRIBUTE_CONST PHPAPI unsigned int php_version_id(void)
{
return PHP_VERSION_ID;
}
+ZEND_ATTRIBUTE_CONST PHPAPI const char *php_build_provider(void)
+{
+#ifdef PHP_BUILD_PROVIDER
+ return PHP_BUILD_PROVIDER;
+#else
+ return NULL;
+#endif
+}
+
PHPAPI char *php_get_version(sapi_module_struct *sapi_module)
{
- char *version_info;
- spprintf(&version_info, 0, "PHP %s (%s) (built: %s) (%s)\nCopyright (c) The PHP Group\n%s%s",
+ smart_string version_info = {0};
+ smart_string_append_printf(&version_info,
+ "PHP %s (%s) (built: %s) (%s)\n",
PHP_VERSION, sapi_module->name, php_build_date,
#ifdef ZTS
"ZTS"
@@ -131,16 +142,15 @@ PHPAPI char *php_get_version(sapi_module_struct *sapi_module)
#ifdef HAVE_GCOV
" GCOV"
#endif
- ,
-#ifdef PHP_BUILD_PROVIDER
- "Built by " PHP_BUILD_PROVIDER "\n"
-#else
- ""
-#endif
- ,
- get_zend_version()
);
- return version_info;
+ smart_string_appends(&version_info, "Copyright (c) The PHP Group\n");
+ if (php_build_provider()) {
+ smart_string_append_printf(&version_info, "Built by %s\n", php_build_provider());
+ }
+ smart_string_appends(&version_info, get_zend_version());
+ smart_string_0(&version_info);
+
+ return version_info.c;
}
PHPAPI void php_print_version(sapi_module_struct *sapi_module)
diff --git a/main/php_main.h b/main/php_main.h
index 889fcf48501f0..a5b049487db23 100644
--- a/main/php_main.h
+++ b/main/php_main.h
@@ -28,13 +28,20 @@ BEGIN_EXTERN_C()
* extensions which want to know the version of PHP at run-time, rather than
* the version they were built with at compile-time.
*/
-PHPAPI const char *php_version(void);
+ZEND_ATTRIBUTE_CONST PHPAPI const char *php_version(void);
/* Returns the PHP version id the engine was built with. This is useful for
* extensions which want to know the version of PHP at run-time, rather than
* the version they were built with at compile-time.
*/
-PHPAPI unsigned int php_version_id(void);
+ZEND_ATTRIBUTE_CONST PHPAPI unsigned int php_version_id(void);
+
+/* Returns the build provider specified at build time. NULL is returned if
+ * no build provider was specified. This is useful for extensions which want
+ * to know the origin of a PHP binary at run-time, for example to provide
+ * statistics.
+ */
+ZEND_ATTRIBUTE_CONST PHPAPI const char *php_build_provider(void);
/* Prints the PHP version string for the -v option. It's in main/ so that
* it can be shared between SAPIs.
| diff --git a/UPGRADING.INTERNALS b/UPGRADING.INTERNALS
index 13b5e6a394434..eb5ccd7bd0bd0 100644
--- a/UPGRADING.INTERNALS
+++ b/UPGRADING.INTERNALS
@@ -23,6 +23,8 @@ PHP 8.5 INTERNALS UPGRADE NOTES
for fake closures.
. Added smart_string_append_printf() matching smart_str_append_printf() for
char* instead of zend_string*-based smart strings.
+ . Added php_build_provider() to retrieve the value of PHP_BUILD_PROVIDER at
+ runtime.
========================
2. Build system changes
diff --git a/ext/standard/info.c b/ext/standard/info.c
index 0211265f954a9..952f0f92fe6e2 100644
--- a/ext/standard/info.c
+++ b/ext/standard/info.c
@@ -805,9 +805,9 @@ PHPAPI ZEND_COLD void php_print_info(int flag)
#ifdef PHP_BUILD_SYSTEM
php_info_print_table_row(2, "Build System", PHP_BUILD_SYSTEM);
- php_info_print_table_row(2, "Build Provider", PHP_BUILD_PROVIDER);
+ if (php_build_provider()) {
+ php_info_print_table_row(2, "Build Provider", php_build_provider());
+ }
#ifdef PHP_BUILD_COMPILER
php_info_print_table_row(2, "Compiler", PHP_BUILD_COMPILER);
diff --git a/main/main.c b/main/main.c
index 415cb02185e94..50894939782a0 100644
--- a/main/main.c
+++ b/main/main.c
@@ -74,6 +74,7 @@
#include "zend_dtrace.h"
#include "zend_observer.h"
#include "zend_system_id.h"
+#include "zend_smart_string.h"
#include "php_content_types.h"
#include "php_ticks.h"
@@ -99,20 +100,30 @@ PHPAPI size_t core_globals_offset;
const char php_build_date[] = __DATE__ " " __TIME__;
-PHPAPI const char *php_version(void)
+ZEND_ATTRIBUTE_CONST PHPAPI const char *php_version(void)
return PHP_VERSION;
-PHPAPI unsigned int php_version_id(void)
+ZEND_ATTRIBUTE_CONST PHPAPI unsigned int php_version_id(void)
return PHP_VERSION_ID;
+ return PHP_BUILD_PROVIDER;
+#else
+}
PHPAPI char *php_get_version(sapi_module_struct *sapi_module)
- char *version_info;
- spprintf(&version_info, 0, "PHP %s (%s) (built: %s) (%s)\nCopyright (c) The PHP Group\n%s%s",
+ smart_string version_info = {0};
+ smart_string_append_printf(&version_info,
+ "PHP %s (%s) (built: %s) (%s)\n",
PHP_VERSION, sapi_module->name, php_build_date,
#ifdef ZTS
"ZTS"
@@ -131,16 +142,15 @@ PHPAPI char *php_get_version(sapi_module_struct *sapi_module)
#ifdef HAVE_GCOV
" GCOV"
- "Built by " PHP_BUILD_PROVIDER "\n"
-#else
- ""
- get_zend_version()
);
- return version_info;
+ smart_string_appends(&version_info, "Copyright (c) The PHP Group\n");
+ if (php_build_provider()) {
+ smart_string_append_printf(&version_info, "Built by %s\n", php_build_provider());
+ }
+ smart_string_appends(&version_info, get_zend_version());
+ smart_string_0(&version_info);
+ return version_info.c;
PHPAPI void php_print_version(sapi_module_struct *sapi_module)
diff --git a/main/php_main.h b/main/php_main.h
index 889fcf48501f0..a5b049487db23 100644
--- a/main/php_main.h
+++ b/main/php_main.h
@@ -28,13 +28,20 @@ BEGIN_EXTERN_C()
-PHPAPI const char *php_version(void);
+ZEND_ATTRIBUTE_CONST PHPAPI const char *php_version(void);
/* Returns the PHP version id the engine was built with. This is useful for
-PHPAPI unsigned int php_version_id(void);
+ZEND_ATTRIBUTE_CONST PHPAPI unsigned int php_version_id(void);
+/* Returns the build provider specified at build time. NULL is returned if
+ * to know the origin of a PHP binary at run-time, for example to provide
+ * statistics.
+ */
+ZEND_ATTRIBUTE_CONST PHPAPI const char *php_build_provider(void);
/* Prints the PHP version string for the -v option. It's in main/ so that
* it can be shared between SAPIs. | [
"+ZEND_ATTRIBUTE_CONST PHPAPI const char *php_build_provider(void)",
"+{",
"+#ifdef PHP_BUILD_PROVIDER",
"+\treturn NULL;",
"+#endif",
"+ * no build provider was specified. This is useful for extensions which want"
] | [
58,
59,
60,
63,
64,
121
] | {
"additions": 37,
"author": "TimWolla",
"deletions": 18,
"html_url": "https://github.com/php/php-src/pull/18168",
"issue_id": 18168,
"merged_at": "2025-03-29T12:29:41Z",
"omission_probability": 0.1,
"pr_number": 18168,
"repo": "php/php-src",
"title": "Add `php_build_provider()`",
"total_changes": 55
} |
777 | diff --git a/ext/standard/array.c b/ext/standard/array.c
index 8462492651310..fdabd5d88ab30 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -632,6 +632,18 @@ PHPAPI zend_long php_count_recursive(HashTable *ht) /* {{{ */
}
/* }}} */
+/* Consumes `zv` */
+static zend_always_inline zend_long php_get_long(zval *zv)
+{
+ if (EXPECTED(Z_TYPE_P(zv) == IS_LONG)) {
+ return Z_LVAL_P(zv);
+ } else {
+ zend_long ret = zval_get_long_func(zv, false);
+ zval_ptr_dtor(zv);
+ return ret;
+ }
+}
+
/* {{{ Count the number of elements in a variable (usually an array) */
PHP_FUNCTION(count)
{
@@ -677,8 +689,7 @@ PHP_FUNCTION(count)
zend_function *count_fn = zend_hash_find_ptr(&zobj->ce->function_table, ZSTR_KNOWN(ZEND_STR_COUNT));
zend_call_known_instance_method_with_0_params(count_fn, zobj, &retval);
if (Z_TYPE(retval) != IS_UNDEF) {
- RETVAL_LONG(zval_get_long(&retval));
- zval_ptr_dtor(&retval);
+ RETVAL_LONG(php_get_long(&retval));
}
return;
}
@@ -811,20 +822,14 @@ static inline int php_array_user_compare_unstable(Bucket *f, Bucket *s) /* {{{ *
{
zval args[2];
zval retval;
- bool call_failed;
- ZVAL_COPY(&args[0], &f->val);
- ZVAL_COPY(&args[1], &s->val);
+ ZVAL_COPY_VALUE(&args[0], &f->val);
+ ZVAL_COPY_VALUE(&args[1], &s->val);
BG(user_compare_fci).param_count = 2;
BG(user_compare_fci).params = args;
BG(user_compare_fci).retval = &retval;
- call_failed = zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE || Z_TYPE(retval) == IS_UNDEF;
- zval_ptr_dtor(&args[1]);
- zval_ptr_dtor(&args[0]);
- if (UNEXPECTED(call_failed)) {
- return 0;
- }
+ zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
if (UNEXPECTED(Z_TYPE(retval) == IS_FALSE || Z_TYPE(retval) == IS_TRUE)) {
if (!ARRAYG(compare_deprecation_thrown)) {
@@ -836,23 +841,16 @@ static inline int php_array_user_compare_unstable(Bucket *f, Bucket *s) /* {{{ *
if (Z_TYPE(retval) == IS_FALSE) {
/* Retry with swapped operands. */
- ZVAL_COPY(&args[0], &s->val);
- ZVAL_COPY(&args[1], &f->val);
- call_failed = zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE || Z_TYPE(retval) == IS_UNDEF;
- zval_ptr_dtor(&args[1]);
- zval_ptr_dtor(&args[0]);
- if (call_failed) {
- return 0;
- }
+ ZVAL_COPY_VALUE(&args[0], &s->val);
+ ZVAL_COPY_VALUE(&args[1], &f->val);
+ zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
- zend_long ret = zval_get_long(&retval);
- zval_ptr_dtor(&retval);
+ zend_long ret = php_get_long(&retval);
return -ZEND_NORMALIZE_BOOL(ret);
}
}
- zend_long ret = zval_get_long(&retval);
- zval_ptr_dtor(&retval);
+ zend_long ret = php_get_long(&retval);
return ZEND_NORMALIZE_BOOL(ret);
}
/* }}} */
@@ -929,28 +927,22 @@ static inline int php_array_user_key_compare_unstable(Bucket *f, Bucket *s) /* {
{
zval args[2];
zval retval;
- bool call_failed;
if (f->key == NULL) {
ZVAL_LONG(&args[0], f->h);
} else {
- ZVAL_STR_COPY(&args[0], f->key);
+ ZVAL_STR(&args[0], f->key);
}
if (s->key == NULL) {
ZVAL_LONG(&args[1], s->h);
} else {
- ZVAL_STR_COPY(&args[1], s->key);
+ ZVAL_STR(&args[1], s->key);
}
BG(user_compare_fci).param_count = 2;
BG(user_compare_fci).params = args;
BG(user_compare_fci).retval = &retval;
- call_failed = zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE || Z_TYPE(retval) == IS_UNDEF;
- zval_ptr_dtor(&args[1]);
- zval_ptr_dtor(&args[0]);
- if (UNEXPECTED(call_failed)) {
- return 0;
- }
+ zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
if (UNEXPECTED(Z_TYPE(retval) == IS_FALSE || Z_TYPE(retval) == IS_TRUE)) {
if (!ARRAYG(compare_deprecation_thrown)) {
@@ -965,29 +957,22 @@ static inline int php_array_user_key_compare_unstable(Bucket *f, Bucket *s) /* {
if (s->key == NULL) {
ZVAL_LONG(&args[0], s->h);
} else {
- ZVAL_STR_COPY(&args[0], s->key);
+ ZVAL_STR(&args[0], s->key);
}
if (f->key == NULL) {
ZVAL_LONG(&args[1], f->h);
} else {
- ZVAL_STR_COPY(&args[1], f->key);
+ ZVAL_STR(&args[1], f->key);
}
- call_failed = zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE || Z_TYPE(retval) == IS_UNDEF;
- zval_ptr_dtor(&args[1]);
- zval_ptr_dtor(&args[0]);
- if (call_failed) {
- return 0;
- }
+ zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
- zend_long ret = zval_get_long(&retval);
- zval_ptr_dtor(&retval);
+ zend_long ret = php_get_long(&retval);
return -ZEND_NORMALIZE_BOOL(ret);
}
}
- zend_long result = zval_get_long(&retval);
- zval_ptr_dtor(&retval);
+ zend_long result = php_get_long(&retval);
return ZEND_NORMALIZE_BOOL(result);
}
/* }}} */
@@ -5065,13 +5050,9 @@ static int zval_user_compare(zval *a, zval *b) /* {{{ */
BG(user_compare_fci).params = args;
BG(user_compare_fci).retval = &retval;
- if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache)) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
- zend_long ret = zval_get_long(&retval);
- zval_ptr_dtor(&retval);
- return ZEND_NORMALIZE_BOOL(ret);
- } else {
- return 0;
- }
+ zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache));
+ zend_long ret = php_get_long(&retval);
+ return ZEND_NORMALIZE_BOOL(ret);
}
/* }}} */
| diff --git a/ext/standard/array.c b/ext/standard/array.c
index 8462492651310..fdabd5d88ab30 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -632,6 +632,18 @@ PHPAPI zend_long php_count_recursive(HashTable *ht) /* {{{ */
+/* Consumes `zv` */
+static zend_always_inline zend_long php_get_long(zval *zv)
+{
+ if (EXPECTED(Z_TYPE_P(zv) == IS_LONG)) {
+ return Z_LVAL_P(zv);
+ } else {
+ zend_long ret = zval_get_long_func(zv, false);
+ zval_ptr_dtor(zv);
+ }
+}
+
/* {{{ Count the number of elements in a variable (usually an array) */
PHP_FUNCTION(count)
@@ -677,8 +689,7 @@ PHP_FUNCTION(count)
zend_function *count_fn = zend_hash_find_ptr(&zobj->ce->function_table, ZSTR_KNOWN(ZEND_STR_COUNT));
zend_call_known_instance_method_with_0_params(count_fn, zobj, &retval);
if (Z_TYPE(retval) != IS_UNDEF) {
- RETVAL_LONG(zval_get_long(&retval));
- zval_ptr_dtor(&retval);
+ RETVAL_LONG(php_get_long(&retval));
}
return;
@@ -811,20 +822,14 @@ static inline int php_array_user_compare_unstable(Bucket *f, Bucket *s) /* {{{ *
- ZVAL_COPY(&args[0], &f->val);
+ ZVAL_COPY_VALUE(&args[0], &f->val);
@@ -836,23 +841,16 @@ static inline int php_array_user_compare_unstable(Bucket *f, Bucket *s) /* {{{ *
if (Z_TYPE(retval) == IS_FALSE) {
/* Retry with swapped operands. */
- ZVAL_COPY(&args[0], &s->val);
- ZVAL_COPY(&args[1], &f->val);
+ ZVAL_COPY_VALUE(&args[1], &f->val);
- zend_long ret = zval_get_long(&retval);
return ZEND_NORMALIZE_BOOL(ret);
@@ -929,28 +927,22 @@ static inline int php_array_user_key_compare_unstable(Bucket *f, Bucket *s) /* {
if (f->key == NULL) {
ZVAL_LONG(&args[0], f->h);
- ZVAL_STR_COPY(&args[0], f->key);
+ ZVAL_STR(&args[0], f->key);
if (s->key == NULL) {
ZVAL_LONG(&args[1], s->h);
- ZVAL_STR_COPY(&args[1], s->key);
+ ZVAL_STR(&args[1], s->key);
@@ -965,29 +957,22 @@ static inline int php_array_user_key_compare_unstable(Bucket *f, Bucket *s) /* {
if (s->key == NULL) {
ZVAL_LONG(&args[0], s->h);
+ ZVAL_STR(&args[0], s->key);
if (f->key == NULL) {
ZVAL_LONG(&args[1], f->h);
- ZVAL_STR_COPY(&args[1], f->key);
+ ZVAL_STR(&args[1], f->key);
- zend_long result = zval_get_long(&retval);
+ zend_long result = php_get_long(&retval);
return ZEND_NORMALIZE_BOOL(result);
@@ -5065,13 +5050,9 @@ static int zval_user_compare(zval *a, zval *b) /* {{{ */
- if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache)) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
- zend_long ret = zval_get_long(&retval);
- zval_ptr_dtor(&retval);
- return ZEND_NORMALIZE_BOOL(ret);
- } else {
+ return ZEND_NORMALIZE_BOOL(ret); | [
"+\t\treturn ret;",
"-\tZVAL_COPY(&args[1], &s->val);",
"+\tZVAL_COPY_VALUE(&args[1], &s->val);",
"+\t\t\tZVAL_COPY_VALUE(&args[0], &s->val);",
"-\t\t\t\tZVAL_STR_COPY(&args[0], s->key);"
] | [
16,
40,
42,
69,
122
] | {
"additions": 32,
"author": "nielsdos",
"deletions": 51,
"html_url": "https://github.com/php/php-src/pull/18166",
"issue_id": 18166,
"merged_at": "2025-03-29T00:02:17Z",
"omission_probability": 0.1,
"pr_number": 18166,
"repo": "php/php-src",
"title": "Improve performance of user-callbacked sort functions",
"total_changes": 83
} |
778 | diff --git a/ext/pdo_pgsql/pgsql_driver.c b/ext/pdo_pgsql/pgsql_driver.c
index dd3b9535a1626..4895463db4b08 100644
--- a/ext/pdo_pgsql/pgsql_driver.c
+++ b/ext/pdo_pgsql/pgsql_driver.c
@@ -619,27 +619,29 @@ static bool pgsql_handle_rollback(pdo_dbh_t *dbh)
static bool _pdo_pgsql_send_copy_data(pdo_pgsql_db_handle *H, zval *line) {
size_t query_len;
- char *query;
+ zend_string *query;
if (!try_convert_to_string(line)) {
return false;
}
query_len = Z_STRLEN_P(line);
- query = emalloc(query_len + 2); /* room for \n\0 */
- memcpy(query, Z_STRVAL_P(line), query_len);
+ query = zend_string_alloc(query_len + 2, false); /* room for \n\0 */
+ memcpy(ZSTR_VAL(query), Z_STRVAL_P(line), query_len + 1);
+ ZSTR_LEN(query) = query_len;
- if (query[query_len - 1] != '\n') {
- query[query_len++] = '\n';
+ if (query_len > 0 && ZSTR_VAL(query)[query_len - 1] != '\n') {
+ ZSTR_VAL(query)[query_len] = '\n';
+ ZSTR_VAL(query)[query_len + 1] = '\0';
+ ZSTR_LEN(query) ++;
}
- query[query_len] = '\0';
- if (PQputCopyData(H->server, query, query_len) != 1) {
- efree(query);
+ if (PQputCopyData(H->server, ZSTR_VAL(query), ZSTR_LEN(query)) != 1) {
+ zend_string_release_ex(query, false);
return false;
}
- efree(query);
+ zend_string_release_ex(query, false);
return true;
}
| diff --git a/ext/pdo_pgsql/pgsql_driver.c b/ext/pdo_pgsql/pgsql_driver.c
index dd3b9535a1626..4895463db4b08 100644
--- a/ext/pdo_pgsql/pgsql_driver.c
+++ b/ext/pdo_pgsql/pgsql_driver.c
@@ -619,27 +619,29 @@ static bool pgsql_handle_rollback(pdo_dbh_t *dbh)
static bool _pdo_pgsql_send_copy_data(pdo_pgsql_db_handle *H, zval *line) {
size_t query_len;
- char *query;
+ zend_string *query;
if (!try_convert_to_string(line)) {
query_len = Z_STRLEN_P(line);
- query = emalloc(query_len + 2); /* room for \n\0 */
- memcpy(query, Z_STRVAL_P(line), query_len);
+ query = zend_string_alloc(query_len + 2, false); /* room for \n\0 */
+ memcpy(ZSTR_VAL(query), Z_STRVAL_P(line), query_len + 1);
+ ZSTR_LEN(query) = query_len;
- if (query[query_len - 1] != '\n') {
+ if (query_len > 0 && ZSTR_VAL(query)[query_len - 1] != '\n') {
+ ZSTR_VAL(query)[query_len] = '\n';
+ ZSTR_VAL(query)[query_len + 1] = '\0';
+ ZSTR_LEN(query) ++;
- query[query_len] = '\0';
- if (PQputCopyData(H->server, query, query_len) != 1) {
- efree(query);
+ if (PQputCopyData(H->server, ZSTR_VAL(query), ZSTR_LEN(query)) != 1) {
+ zend_string_release_ex(query, false);
- efree(query);
+ zend_string_release_ex(query, false);
return true;
} | [
"-\t\tquery[query_len++] = '\\n';"
] | [
23
] | {
"additions": 11,
"author": "devnexen",
"deletions": 9,
"html_url": "https://github.com/php/php-src/pull/18175",
"issue_id": 18175,
"merged_at": "2025-03-28T18:24:46Z",
"omission_probability": 0.1,
"pr_number": 18175,
"repo": "php/php-src",
"title": "ext/pdo_pgsql: updating copy from according to pgsql extension workflow.",
"total_changes": 20
} |
779 | diff --git a/ext/standard/array.c b/ext/standard/array.c
index 8462492651310..25b1b6088378f 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -6736,16 +6736,12 @@ PHP_FUNCTION(array_map)
ZEND_PARSE_PARAMETERS_END();
if (n_arrays == 1) {
- zend_ulong num_key;
- zend_string *str_key;
- zval *zv, arg;
- int ret;
-
if (Z_TYPE(arrays[0]) != IS_ARRAY) {
zend_argument_type_error(2, "must be of type array, %s given", zend_zval_value_name(&arrays[0]));
RETURN_THROWS();
}
- maxlen = zend_hash_num_elements(Z_ARRVAL(arrays[0]));
+ const HashTable *input = Z_ARRVAL(arrays[0]);
+ maxlen = zend_hash_num_elements(input);
/* Short-circuit: if no callback and only one array, just return it. */
if (!ZEND_FCI_INITIALIZED(fci) || !maxlen) {
@@ -6753,27 +6749,60 @@ PHP_FUNCTION(array_map)
return;
}
- array_init_size(return_value, maxlen);
- zend_hash_real_init(Z_ARRVAL_P(return_value), HT_IS_PACKED(Z_ARRVAL(arrays[0])));
-
- ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(arrays[0]), num_key, str_key, zv) {
- fci.retval = &result;
- fci.param_count = 1;
- fci.params = &arg;
-
- ZVAL_COPY(&arg, zv);
- ret = zend_call_function(&fci, &fci_cache);
- i_zval_ptr_dtor(&arg);
- if (ret != SUCCESS || Z_TYPE(result) == IS_UNDEF) {
- zend_array_destroy(Z_ARR_P(return_value));
- RETURN_NULL();
- }
- if (str_key) {
- _zend_hash_append(Z_ARRVAL_P(return_value), str_key, &result);
- } else {
- zend_hash_index_add_new(Z_ARRVAL_P(return_value), num_key, &result);
- }
- } ZEND_HASH_FOREACH_END();
+ fci.retval = &result;
+ fci.param_count = 1;
+
+ if (HT_IS_PACKED(input)) {
+ array_init_size(return_value, input->nNumUsed);
+ HashTable *output = Z_ARRVAL_P(return_value);
+ zend_hash_real_init_packed(output);
+
+ uint32_t undefs = 0;
+ ZEND_HASH_FILL_PACKED(output) {
+ /* Can't use ZEND_HASH_PACKED_FOREACH_VAL() because we need to also account for the UNDEF values
+ * so the keys in the output array will match those of the input array. */
+ for (zval *cur = input->arPacked, *end = input->arPacked + input->nNumUsed; cur != end; cur++) {
+ if (EXPECTED(!Z_ISUNDEF_P(cur))) {
+ fci.params = cur;
+ zend_result ret = zend_call_function(&fci, &fci_cache);
+ ZEND_ASSERT(ret == SUCCESS);
+ ZEND_IGNORE_VALUE(ret);
+ if (UNEXPECTED(Z_ISUNDEF(result))) {
+ ZEND_HASH_FILL_FINISH();
+ zend_array_destroy(output);
+ RETURN_NULL();
+ }
+ } else {
+ ZVAL_UNDEF(&result);
+ undefs++;
+ }
+ ZEND_HASH_FILL_ADD(&result);
+ }
+ } ZEND_HASH_FILL_END();
+ output->nNumOfElements -= undefs;
+ } else {
+ zend_ulong num_key;
+ zend_string *str_key;
+
+ array_init_size(return_value, maxlen);
+ HashTable *output = Z_ARRVAL_P(return_value);
+ zend_hash_real_init_mixed(output);
+
+ ZEND_HASH_MAP_FOREACH_KEY_VAL(input, num_key, str_key, fci.params) {
+ zend_result ret = zend_call_function(&fci, &fci_cache);
+ ZEND_ASSERT(ret == SUCCESS);
+ ZEND_IGNORE_VALUE(ret);
+ if (UNEXPECTED(Z_ISUNDEF(result))) {
+ zend_array_destroy(output);
+ RETURN_NULL();
+ }
+ if (str_key) {
+ _zend_hash_append(output, str_key, &result);
+ } else {
+ zend_hash_index_add_new(output, num_key, &result);
+ }
+ } ZEND_HASH_FOREACH_END();
+ }
} else {
uint32_t *array_pos = (HashPosition *)ecalloc(n_arrays, sizeof(HashPosition));
@@ -6874,7 +6903,11 @@ PHP_FUNCTION(array_map)
fci.param_count = n_arrays;
fci.params = params;
- if (zend_call_function(&fci, &fci_cache) != SUCCESS || Z_TYPE(result) == IS_UNDEF) {
+ zend_result ret = zend_call_function(&fci, &fci_cache);
+ ZEND_ASSERT(ret == SUCCESS);
+ ZEND_IGNORE_VALUE(ret);
+
+ if (Z_TYPE(result) == IS_UNDEF) {
efree(array_pos);
zend_array_destroy(Z_ARR_P(return_value));
for (i = 0; i < n_arrays; i++) {
| diff --git a/ext/standard/array.c b/ext/standard/array.c
index 8462492651310..25b1b6088378f 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -6736,16 +6736,12 @@ PHP_FUNCTION(array_map)
ZEND_PARSE_PARAMETERS_END();
if (n_arrays == 1) {
- zend_string *str_key;
- zval *zv, arg;
- int ret;
if (Z_TYPE(arrays[0]) != IS_ARRAY) {
zend_argument_type_error(2, "must be of type array, %s given", zend_zval_value_name(&arrays[0]));
RETURN_THROWS();
- maxlen = zend_hash_num_elements(Z_ARRVAL(arrays[0]));
+ const HashTable *input = Z_ARRVAL(arrays[0]);
+ maxlen = zend_hash_num_elements(input);
/* Short-circuit: if no callback and only one array, just return it. */
if (!ZEND_FCI_INITIALIZED(fci) || !maxlen) {
@@ -6753,27 +6749,60 @@ PHP_FUNCTION(array_map)
return;
- array_init_size(return_value, maxlen);
- zend_hash_real_init(Z_ARRVAL_P(return_value), HT_IS_PACKED(Z_ARRVAL(arrays[0])));
- ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(arrays[0]), num_key, str_key, zv) {
- fci.param_count = 1;
- fci.params = &arg;
- ZVAL_COPY(&arg, zv);
- i_zval_ptr_dtor(&arg);
- if (ret != SUCCESS || Z_TYPE(result) == IS_UNDEF) {
- zend_array_destroy(Z_ARR_P(return_value));
- RETURN_NULL();
- if (str_key) {
- _zend_hash_append(Z_ARRVAL_P(return_value), str_key, &result);
- } else {
- zend_hash_index_add_new(Z_ARRVAL_P(return_value), num_key, &result);
- } ZEND_HASH_FOREACH_END();
+ fci.retval = &result;
+ fci.param_count = 1;
+ if (HT_IS_PACKED(input)) {
+ array_init_size(return_value, input->nNumUsed);
+ zend_hash_real_init_packed(output);
+ uint32_t undefs = 0;
+ /* Can't use ZEND_HASH_PACKED_FOREACH_VAL() because we need to also account for the UNDEF values
+ * so the keys in the output array will match those of the input array. */
+ for (zval *cur = input->arPacked, *end = input->arPacked + input->nNumUsed; cur != end; cur++) {
+ if (EXPECTED(!Z_ISUNDEF_P(cur))) {
+ fci.params = cur;
+ zend_result ret = zend_call_function(&fci, &fci_cache);
+ ZEND_ASSERT(ret == SUCCESS);
+ ZEND_IGNORE_VALUE(ret);
+ if (UNEXPECTED(Z_ISUNDEF(result))) {
+ ZEND_HASH_FILL_FINISH();
+ zend_array_destroy(output);
+ RETURN_NULL();
+ } else {
+ ZVAL_UNDEF(&result);
+ }
+ ZEND_HASH_FILL_ADD(&result);
+ } ZEND_HASH_FILL_END();
+ output->nNumOfElements -= undefs;
+ zend_ulong num_key;
+ zend_string *str_key;
+ zend_hash_real_init_mixed(output);
+ ZEND_HASH_MAP_FOREACH_KEY_VAL(input, num_key, str_key, fci.params) {
+ if (UNEXPECTED(Z_ISUNDEF(result))) {
+ if (str_key) {
+ _zend_hash_append(output, str_key, &result);
+ zend_hash_index_add_new(output, num_key, &result);
+ } ZEND_HASH_FOREACH_END();
+ }
} else {
uint32_t *array_pos = (HashPosition *)ecalloc(n_arrays, sizeof(HashPosition));
@@ -6874,7 +6903,11 @@ PHP_FUNCTION(array_map)
fci.param_count = n_arrays;
fci.params = params;
- if (zend_call_function(&fci, &fci_cache) != SUCCESS || Z_TYPE(result) == IS_UNDEF) {
+ if (Z_TYPE(result) == IS_UNDEF) {
efree(array_pos);
zend_array_destroy(Z_ARR_P(return_value));
for (i = 0; i < n_arrays; i++) { | [
"-\t\tzend_ulong num_key;",
"-\t\t\tfci.retval = &result;",
"-\t\t\tret = zend_call_function(&fci, &fci_cache);",
"+\t\t\tZEND_HASH_FILL_PACKED(output) {",
"+\t\t\t\t\t\t}",
"+\t\t\t\t\t\tundefs++;",
"+\t\t} else {",
"+\t\t\tarray_init_size(return_value, maxlen);",
"+\t\t\t\t\tzend_array_destroy(output);",
"+\t\t\t\t\tRETURN_NULL();",
"+\t\t\t\t} else {"
] | [
8,
31,
36,
57,
70,
73,
79,
83,
92,
93,
97
] | {
"additions": 61,
"author": "nielsdos",
"deletions": 28,
"html_url": "https://github.com/php/php-src/pull/18158",
"issue_id": 18158,
"merged_at": "2025-03-28T18:09:49Z",
"omission_probability": 0.1,
"pr_number": 18158,
"repo": "php/php-src",
"title": "Improve performance of array_map()",
"total_changes": 89
} |
780 | diff --git a/ext/date/php_date.c b/ext/date/php_date.c
index ed89c9d494a6f..a533552621f2a 100644
--- a/ext/date/php_date.c
+++ b/ext/date/php_date.c
@@ -673,7 +673,7 @@ static const char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib
/* }}} */
/* {{{ date_format - (gm)date helper */
-static zend_string *date_format(const char *format, size_t format_len, timelib_time *t, bool localtime)
+static zend_string *date_format(const char *format, size_t format_len, const timelib_time *t, bool localtime)
{
smart_str string = {0};
size_t i;
@@ -845,7 +845,7 @@ static zend_string *date_format(const char *format, size_t format_len, timelib_t
return string.s;
}
-PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, php_date_obj *date_obj)
+PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, const php_date_obj *date_obj)
{
if (!date_obj->time) {
return NULL;
@@ -2807,7 +2807,7 @@ PHP_METHOD(DateTimeImmutable, createFromTimestamp)
}
/* }}} */
-static bool php_date_initialize_from_hash(php_date_obj **dateobj, HashTable *myht)
+static bool php_date_initialize_from_hash(php_date_obj **dateobj, const HashTable *myht)
{
zval *z_date;
zval *z_timezone_type;
@@ -2948,7 +2948,7 @@ PHP_METHOD(DateTimeImmutable, __serialize)
}
/* }}} */
-static bool date_time_is_internal_property(zend_string *name)
+static bool date_time_is_internal_property(const zend_string *name)
{
if (
zend_string_equals_literal(name, "date") ||
@@ -2960,7 +2960,7 @@ static bool date_time_is_internal_property(zend_string *name)
return 0;
}
-static void restore_custom_datetime_properties(zval *object, HashTable *myht)
+static void restore_custom_datetime_properties(zval *object, const HashTable *myht)
{
zend_string *prop_name;
zval *prop_val;
@@ -2978,15 +2978,13 @@ PHP_METHOD(DateTime, __unserialize)
{
zval *object = ZEND_THIS;
php_date_obj *dateobj;
- zval *array;
HashTable *myht;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_ARRAY(array)
+ Z_PARAM_ARRAY_HT(myht)
ZEND_PARSE_PARAMETERS_END();
dateobj = Z_PHPDATE_P(object);
- myht = Z_ARRVAL_P(array);
if (!php_date_initialize_from_hash(&dateobj, myht)) {
zend_throw_error(NULL, "Invalid serialization data for DateTime object");
@@ -3002,15 +3000,13 @@ PHP_METHOD(DateTimeImmutable, __unserialize)
{
zval *object = ZEND_THIS;
php_date_obj *dateobj;
- zval *array;
HashTable *myht;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_ARRAY(array)
+ Z_PARAM_ARRAY_HT(myht)
ZEND_PARSE_PARAMETERS_END();
dateobj = Z_PHPDATE_P(object);
- myht = Z_ARRVAL_P(array);
if (!php_date_initialize_from_hash(&dateobj, myht)) {
zend_throw_error(NULL, "Invalid serialization data for DateTimeImmutable object");
@@ -3027,7 +3023,7 @@ static void php_do_date_time_wakeup(INTERNAL_FUNCTION_PARAMETERS, const char *cl
{
zval *object = ZEND_THIS;
php_date_obj *dateobj;
- HashTable *myht;
+ const HashTable *myht;
ZEND_PARSE_PARAMETERS_NONE();
@@ -3057,7 +3053,7 @@ PHP_METHOD(DateTimeImmutable, __wakeup)
/* }}} */
/* Helper function used to add an associative array of warnings and errors to a zval */
-static void zval_from_error_container(zval *z, timelib_error_container *error) /* {{{ */
+static void zval_from_error_container(zval *z, const timelib_error_container *error) /* {{{ */
{
int i;
zval element;
@@ -3498,7 +3494,7 @@ PHP_METHOD(DateTimeImmutable, sub)
}
/* }}} */
-static void set_timezone_from_timelib_time(php_timezone_obj *tzobj, timelib_time *t)
+static void set_timezone_from_timelib_time(php_timezone_obj *tzobj, const timelib_time *t)
{
/* Free abbreviation if already set */
if (tzobj->initialized && tzobj->type == TIMELIB_ZONETYPE_ABBR) {
@@ -4057,7 +4053,7 @@ PHP_METHOD(DateTimeZone, __construct)
}
/* }}} */
-static bool php_date_timezone_initialize_from_hash(zval **return_value, php_timezone_obj **tzobj, HashTable *myht) /* {{{ */
+static bool php_date_timezone_initialize_from_hash(zval **return_value, php_timezone_obj **tzobj, const HashTable *myht) /* {{{ */
{
zval *z_timezone_type;
@@ -4087,15 +4083,12 @@ static bool php_date_timezone_initialize_from_hash(zval **return_value, php_time
PHP_METHOD(DateTimeZone, __set_state)
{
php_timezone_obj *tzobj;
- zval *array;
HashTable *myht;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_ARRAY(array)
+ Z_PARAM_ARRAY_HT(myht)
ZEND_PARSE_PARAMETERS_END();
- myht = Z_ARRVAL_P(array);
-
php_date_instantiate(date_ce_timezone, return_value);
tzobj = Z_PHPTIMEZONE_P(return_value);
if (!php_date_timezone_initialize_from_hash(&return_value, &tzobj, myht)) {
@@ -4110,7 +4103,7 @@ PHP_METHOD(DateTimeZone, __wakeup)
{
zval *object = ZEND_THIS;
php_timezone_obj *tzobj;
- HashTable *myht;
+ const HashTable *myht;
ZEND_PARSE_PARAMETERS_NONE();
@@ -4145,7 +4138,7 @@ PHP_METHOD(DateTimeZone, __serialize)
}
/* }}} */
-static bool date_timezone_is_internal_property(zend_string *name)
+static bool date_timezone_is_internal_property(const zend_string *name)
{
if (
zend_string_equals_literal(name, "timezone_type") ||
@@ -4156,7 +4149,7 @@ static bool date_timezone_is_internal_property(zend_string *name)
return 0;
}
-static void restore_custom_datetimezone_properties(zval *object, HashTable *myht)
+static void restore_custom_datetimezone_properties(zval *object, const HashTable *myht)
{
zend_string *prop_name;
zval *prop_val;
@@ -4174,15 +4167,13 @@ PHP_METHOD(DateTimeZone, __unserialize)
{
zval *object = ZEND_THIS;
php_timezone_obj *tzobj;
- zval *array;
HashTable *myht;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_ARRAY(array)
+ Z_PARAM_ARRAY_HT(myht)
ZEND_PARSE_PARAMETERS_END();
tzobj = Z_PHPTIMEZONE_P(object);
- myht = Z_ARRVAL_P(array);
if (!php_date_timezone_initialize_from_hash(&object, &tzobj, myht)) {
zend_throw_error(NULL, "Invalid serialization data for DateTimeZone object");
@@ -4422,7 +4413,7 @@ PHP_FUNCTION(timezone_location_get)
}
/* }}} */
-static bool date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, size_t format_length) /* {{{ */
+static bool date_interval_initialize(timelib_rel_time **rt, const char *format, size_t format_length) /* {{{ */
{
timelib_time *b = NULL, *e = NULL;
timelib_rel_time *p = NULL;
@@ -4607,10 +4598,10 @@ PHP_METHOD(DateInterval, __construct)
}
/* }}} */
-static void php_date_interval_initialize_from_hash(zval **return_value, php_interval_obj **intobj, HashTable *myht) /* {{{ */
+static void php_date_interval_initialize_from_hash(zval **return_value, php_interval_obj **intobj, const HashTable *myht) /* {{{ */
{
/* If we have a date_string, use that instead */
- zval *date_str = zend_hash_str_find(myht, "date_string", strlen("date_string"));
+ const zval *date_str = zend_hash_str_find(myht, "date_string", strlen("date_string"));
if (date_str && Z_TYPE_P(date_str) == IS_STRING) {
timelib_time *time;
timelib_error_container *err = NULL;
@@ -4708,7 +4699,7 @@ static void php_date_interval_initialize_from_hash(zval **return_value, php_inte
PHP_DATE_INTERVAL_READ_PROPERTY("i", i, timelib_sll, -1)
PHP_DATE_INTERVAL_READ_PROPERTY("s", s, timelib_sll, -1)
{
- zval *z_arg = zend_hash_str_find(myht, "f", sizeof("f") - 1);
+ const zval *z_arg = zend_hash_str_find(myht, "f", sizeof("f") - 1);
if (z_arg) {
(*intobj)->diff->us = zend_dval_to_lval(zval_get_double(z_arg) * 1000000.0);
}
@@ -4723,7 +4714,7 @@ static void php_date_interval_initialize_from_hash(zval **return_value, php_inte
PHP_DATE_INTERVAL_READ_PROPERTY("have_weekday_relative", have_weekday_relative, unsigned int, 0);
PHP_DATE_INTERVAL_READ_PROPERTY("have_special_relative", have_special_relative, unsigned int, 0);
{
- zval *z_arg = zend_hash_str_find(myht, "civil_or_wall", sizeof("civil_or_wall") - 1);
+ const zval *z_arg = zend_hash_str_find(myht, "civil_or_wall", sizeof("civil_or_wall") - 1);
(*intobj)->civil_or_wall = PHP_DATE_CIVIL;
if (z_arg) {
zend_long val = zval_get_long(z_arg);
@@ -4738,15 +4729,12 @@ static void php_date_interval_initialize_from_hash(zval **return_value, php_inte
PHP_METHOD(DateInterval, __set_state)
{
php_interval_obj *intobj;
- zval *array;
HashTable *myht;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_ARRAY(array)
+ Z_PARAM_ARRAY_HT(myht)
ZEND_PARSE_PARAMETERS_END();
- myht = Z_ARRVAL_P(array);
-
php_date_instantiate(date_ce_interval, return_value);
intobj = Z_PHPINTERVAL_P(return_value);
php_date_interval_initialize_from_hash(&return_value, &intobj, myht);
@@ -4773,7 +4761,7 @@ PHP_METHOD(DateInterval, __serialize)
}
/* }}} */
-static bool date_interval_is_internal_property(zend_string *name)
+static bool date_interval_is_internal_property(const zend_string *name)
{
if (
zend_string_equals_literal(name, "date_string") ||
@@ -4793,7 +4781,7 @@ static bool date_interval_is_internal_property(zend_string *name)
return 0;
}
-static void restore_custom_dateinterval_properties(zval *object, HashTable *myht)
+static void restore_custom_dateinterval_properties(zval *object, const HashTable *myht)
{
zend_string *prop_name;
zval *prop_val;
@@ -4812,15 +4800,13 @@ PHP_METHOD(DateInterval, __unserialize)
{
zval *object = ZEND_THIS;
php_interval_obj *intervalobj;
- zval *array;
HashTable *myht;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_ARRAY(array)
+ Z_PARAM_ARRAY_HT(myht)
ZEND_PARSE_PARAMETERS_END();
intervalobj = Z_PHPINTERVAL_P(object);
- myht = Z_ARRVAL_P(array);
php_date_interval_initialize_from_hash(&object, &intervalobj, myht);
restore_custom_dateinterval_properties(object, myht);
@@ -4832,7 +4818,7 @@ PHP_METHOD(DateInterval, __wakeup)
{
zval *object = ZEND_THIS;
php_interval_obj *intobj;
- HashTable *myht;
+ const HashTable *myht;
ZEND_PARSE_PARAMETERS_NONE();
@@ -4924,7 +4910,7 @@ PHP_METHOD(DateInterval, createFromDateString)
/* }}} */
/* {{{ date_interval_format - */
-static zend_string *date_interval_format(char *format, size_t format_len, timelib_rel_time *t)
+static zend_string *date_interval_format(const char *format, size_t format_len, timelib_rel_time *t)
{
smart_str string = {0};
size_t i;
@@ -4998,7 +4984,7 @@ PHP_FUNCTION(date_interval_format)
{
zval *object;
php_interval_obj *diobj;
- char *format;
+ const char *format;
size_t format_len;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) {
@@ -5011,7 +4997,7 @@ PHP_FUNCTION(date_interval_format)
}
/* }}} */
-static bool date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, zend_long *recurrences, /*const*/ char *format, size_t format_length) /* {{{ */
+static bool date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, zend_long *recurrences, const char *format, size_t format_length) /* {{{ */
{
timelib_time *b = NULL, *e = NULL;
timelib_rel_time *p = NULL;
@@ -5044,7 +5030,7 @@ static bool date_period_initialize(timelib_time **st, timelib_time **et, timelib
return retval;
} /* }}} */
-static bool date_period_init_iso8601_string(php_period_obj *dpobj, zend_class_entry* base_ce, char *isostr, size_t isostr_len, zend_long options, zend_long *recurrences)
+static bool date_period_init_iso8601_string(php_period_obj *dpobj, zend_class_entry* base_ce, const char *isostr, size_t isostr_len, zend_long *recurrences)
{
if (!date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), recurrences, isostr, isostr_len)) {
return false;
@@ -5130,7 +5116,7 @@ PHP_METHOD(DatePeriod, createFromISO8601String)
dpobj->current = NULL;
- if (!date_period_init_iso8601_string(dpobj, date_ce_immutable, isostr, isostr_len, options, &recurrences)) {
+ if (!date_period_init_iso8601_string(dpobj, date_ce_immutable, isostr, isostr_len, &recurrences)) {
RETURN_THROWS();
}
@@ -5169,7 +5155,7 @@ PHP_METHOD(DatePeriod, __construct)
RETURN_THROWS();
}
- if (!date_period_init_iso8601_string(dpobj, date_ce_date, isostr, isostr_len, options, &recurrences)) {
+ if (!date_period_init_iso8601_string(dpobj, date_ce_date, isostr, isostr_len, &recurrences)) {
RETURN_THROWS();
}
} else {
@@ -5305,7 +5291,7 @@ PHP_METHOD(DatePeriod, getIterator)
zend_create_internal_iterator_zval(return_value, ZEND_THIS);
}
-static int check_id_allowed(char *id, zend_long what) /* {{{ */
+static bool check_id_allowed(const char *id, zend_long what) /* {{{ */
{
if ((what & PHP_DATE_TIMEZONE_GROUP_AFRICA) && strncasecmp(id, "Africa/", 7) == 0) return 1;
if ((what & PHP_DATE_TIMEZONE_GROUP_AMERICA) && strncasecmp(id, "America/", 8) == 0) return 1;
@@ -5711,7 +5697,7 @@ static void date_period_object_to_hash(php_period_obj *period_obj, HashTable *pr
zend_hash_str_update(props, "include_end_date", sizeof("include_end_date")-1, &zv);
}
-static bool php_date_period_initialize_from_hash(php_period_obj *period_obj, HashTable *myht) /* {{{ */
+static bool php_date_period_initialize_from_hash(php_period_obj *period_obj, const HashTable *myht) /* {{{ */
{
zval *ht_entry;
@@ -5835,15 +5821,12 @@ static bool php_date_period_initialize_from_hash(php_period_obj *period_obj, Has
PHP_METHOD(DatePeriod, __set_state)
{
php_period_obj *period_obj;
- zval *array;
HashTable *myht;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_ARRAY(array)
+ Z_PARAM_ARRAY_HT(myht)
ZEND_PARSE_PARAMETERS_END();
- myht = Z_ARRVAL_P(array);
-
object_init_ex(return_value, date_ce_period);
period_obj = Z_PHPPERIOD_P(return_value);
if (!php_date_period_initialize_from_hash(period_obj, myht)) {
@@ -5877,7 +5860,7 @@ PHP_METHOD(DatePeriod, __serialize)
* Common for date_period_read_property(), date_period_write_property(), and
* restore_custom_dateperiod_properties functions
*/
-static bool date_period_is_internal_property(zend_string *name)
+static bool date_period_is_internal_property(const zend_string *name)
{
if (
zend_string_equals_literal(name, "start") ||
@@ -5894,7 +5877,7 @@ static bool date_period_is_internal_property(zend_string *name)
}
/* }}} */
-static void restore_custom_dateperiod_properties(zval *object, HashTable *myht)
+static void restore_custom_dateperiod_properties(zval *object, const HashTable *myht)
{
zend_string *prop_name;
zval *prop_val;
@@ -5912,15 +5895,13 @@ PHP_METHOD(DatePeriod, __unserialize)
{
zval *object = ZEND_THIS;
php_period_obj *period_obj;
- zval *array;
HashTable *myht;
ZEND_PARSE_PARAMETERS_START(1, 1)
- Z_PARAM_ARRAY(array)
+ Z_PARAM_ARRAY_HT(myht)
ZEND_PARSE_PARAMETERS_END();
period_obj = Z_PHPPERIOD_P(object);
- myht = Z_ARRVAL_P(array);
if (!php_date_period_initialize_from_hash(period_obj, myht)) {
zend_throw_error(NULL, "Invalid serialization data for DatePeriod object");
@@ -5935,7 +5916,7 @@ PHP_METHOD(DatePeriod, __wakeup)
{
zval *object = ZEND_THIS;
php_period_obj *period_obj;
- HashTable *myht;
+ const HashTable *myht;
ZEND_PARSE_PARAMETERS_NONE();
diff --git a/ext/date/php_date.h b/ext/date/php_date.h
index f1b7c892001a9..f5f43bc7dfb0f 100644
--- a/ext/date/php_date.h
+++ b/ext/date/php_date.h
@@ -89,9 +89,9 @@ static inline php_timezone_obj *php_timezone_obj_from_obj(zend_object *obj) {
struct _php_interval_obj {
timelib_rel_time *diff;
int civil_or_wall;
+ bool initialized;
bool from_string;
zend_string *date_string;
- bool initialized;
zend_object std;
};
@@ -140,7 +140,7 @@ PHPAPI int php_idate(char format, time_t ts, bool localtime);
PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, bool gm);
PHPAPI zend_string *php_format_date(const char *format, size_t format_len, time_t ts, bool localtime);
-PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, php_date_obj *date_obj);
+PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, const php_date_obj *date_obj);
/* Mechanism to set new TZ database */
PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb);
| diff --git a/ext/date/php_date.c b/ext/date/php_date.c
index ed89c9d494a6f..a533552621f2a 100644
--- a/ext/date/php_date.c
+++ b/ext/date/php_date.c
@@ -673,7 +673,7 @@ static const char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib
/* {{{ date_format - (gm)date helper */
-static zend_string *date_format(const char *format, size_t format_len, timelib_time *t, bool localtime)
+static zend_string *date_format(const char *format, size_t format_len, const timelib_time *t, bool localtime)
@@ -845,7 +845,7 @@ static zend_string *date_format(const char *format, size_t format_len, timelib_t
return string.s;
+PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, const php_date_obj *date_obj)
if (!date_obj->time) {
return NULL;
@@ -2807,7 +2807,7 @@ PHP_METHOD(DateTimeImmutable, createFromTimestamp)
-static bool php_date_initialize_from_hash(php_date_obj **dateobj, HashTable *myht)
+static bool php_date_initialize_from_hash(php_date_obj **dateobj, const HashTable *myht)
zval *z_date;
zval *z_timezone_type;
@@ -2948,7 +2948,7 @@ PHP_METHOD(DateTimeImmutable, __serialize)
-static bool date_time_is_internal_property(zend_string *name)
+static bool date_time_is_internal_property(const zend_string *name)
zend_string_equals_literal(name, "date") ||
@@ -2960,7 +2960,7 @@ static bool date_time_is_internal_property(zend_string *name)
-static void restore_custom_datetime_properties(zval *object, HashTable *myht)
+static void restore_custom_datetime_properties(zval *object, const HashTable *myht)
@@ -2978,15 +2978,13 @@ PHP_METHOD(DateTime, __unserialize)
zend_throw_error(NULL, "Invalid serialization data for DateTime object");
@@ -3002,15 +3000,13 @@ PHP_METHOD(DateTimeImmutable, __unserialize)
zend_throw_error(NULL, "Invalid serialization data for DateTimeImmutable object");
@@ -3027,7 +3023,7 @@ static void php_do_date_time_wakeup(INTERNAL_FUNCTION_PARAMETERS, const char *cl
@@ -3057,7 +3053,7 @@ PHP_METHOD(DateTimeImmutable, __wakeup)
/* Helper function used to add an associative array of warnings and errors to a zval */
int i;
zval element;
@@ -3498,7 +3494,7 @@ PHP_METHOD(DateTimeImmutable, sub)
-static void set_timezone_from_timelib_time(php_timezone_obj *tzobj, timelib_time *t)
/* Free abbreviation if already set */
if (tzobj->initialized && tzobj->type == TIMELIB_ZONETYPE_ABBR) {
@@ -4057,7 +4053,7 @@ PHP_METHOD(DateTimeZone, __construct)
-static bool php_date_timezone_initialize_from_hash(zval **return_value, php_timezone_obj **tzobj, HashTable *myht) /* {{{ */
zval *z_timezone_type;
@@ -4087,15 +4083,12 @@ static bool php_date_timezone_initialize_from_hash(zval **return_value, php_time
PHP_METHOD(DateTimeZone, __set_state)
php_date_instantiate(date_ce_timezone, return_value);
tzobj = Z_PHPTIMEZONE_P(return_value);
if (!php_date_timezone_initialize_from_hash(&return_value, &tzobj, myht)) {
@@ -4110,7 +4103,7 @@ PHP_METHOD(DateTimeZone, __wakeup)
@@ -4145,7 +4138,7 @@ PHP_METHOD(DateTimeZone, __serialize)
-static bool date_timezone_is_internal_property(zend_string *name)
+static bool date_timezone_is_internal_property(const zend_string *name)
zend_string_equals_literal(name, "timezone_type") ||
@@ -4156,7 +4149,7 @@ static bool date_timezone_is_internal_property(zend_string *name)
-static void restore_custom_datetimezone_properties(zval *object, HashTable *myht)
@@ -4174,15 +4167,13 @@ PHP_METHOD(DateTimeZone, __unserialize)
tzobj = Z_PHPTIMEZONE_P(object);
if (!php_date_timezone_initialize_from_hash(&object, &tzobj, myht)) {
zend_throw_error(NULL, "Invalid serialization data for DateTimeZone object");
@@ -4422,7 +4413,7 @@ PHP_FUNCTION(timezone_location_get)
-static bool date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, size_t format_length) /* {{{ */
+static bool date_interval_initialize(timelib_rel_time **rt, const char *format, size_t format_length) /* {{{ */
@@ -4607,10 +4598,10 @@ PHP_METHOD(DateInterval, __construct)
-static void php_date_interval_initialize_from_hash(zval **return_value, php_interval_obj **intobj, HashTable *myht) /* {{{ */
+static void php_date_interval_initialize_from_hash(zval **return_value, php_interval_obj **intobj, const HashTable *myht) /* {{{ */
/* If we have a date_string, use that instead */
- zval *date_str = zend_hash_str_find(myht, "date_string", strlen("date_string"));
+ const zval *date_str = zend_hash_str_find(myht, "date_string", strlen("date_string"));
if (date_str && Z_TYPE_P(date_str) == IS_STRING) {
timelib_time *time;
timelib_error_container *err = NULL;
@@ -4708,7 +4699,7 @@ static void php_date_interval_initialize_from_hash(zval **return_value, php_inte
PHP_DATE_INTERVAL_READ_PROPERTY("i", i, timelib_sll, -1)
PHP_DATE_INTERVAL_READ_PROPERTY("s", s, timelib_sll, -1)
- zval *z_arg = zend_hash_str_find(myht, "f", sizeof("f") - 1);
+ const zval *z_arg = zend_hash_str_find(myht, "f", sizeof("f") - 1);
(*intobj)->diff->us = zend_dval_to_lval(zval_get_double(z_arg) * 1000000.0);
@@ -4723,7 +4714,7 @@ static void php_date_interval_initialize_from_hash(zval **return_value, php_inte
PHP_DATE_INTERVAL_READ_PROPERTY("have_weekday_relative", have_weekday_relative, unsigned int, 0);
PHP_DATE_INTERVAL_READ_PROPERTY("have_special_relative", have_special_relative, unsigned int, 0);
- zval *z_arg = zend_hash_str_find(myht, "civil_or_wall", sizeof("civil_or_wall") - 1);
+ const zval *z_arg = zend_hash_str_find(myht, "civil_or_wall", sizeof("civil_or_wall") - 1);
(*intobj)->civil_or_wall = PHP_DATE_CIVIL;
zend_long val = zval_get_long(z_arg);
@@ -4738,15 +4729,12 @@ static void php_date_interval_initialize_from_hash(zval **return_value, php_inte
PHP_METHOD(DateInterval, __set_state)
php_date_instantiate(date_ce_interval, return_value);
intobj = Z_PHPINTERVAL_P(return_value);
php_date_interval_initialize_from_hash(&return_value, &intobj, myht);
@@ -4773,7 +4761,7 @@ PHP_METHOD(DateInterval, __serialize)
-static bool date_interval_is_internal_property(zend_string *name)
+static bool date_interval_is_internal_property(const zend_string *name)
zend_string_equals_literal(name, "date_string") ||
@@ -4793,7 +4781,7 @@ static bool date_interval_is_internal_property(zend_string *name)
-static void restore_custom_dateinterval_properties(zval *object, HashTable *myht)
+static void restore_custom_dateinterval_properties(zval *object, const HashTable *myht)
@@ -4812,15 +4800,13 @@ PHP_METHOD(DateInterval, __unserialize)
php_interval_obj *intervalobj;
intervalobj = Z_PHPINTERVAL_P(object);
php_date_interval_initialize_from_hash(&object, &intervalobj, myht);
restore_custom_dateinterval_properties(object, myht);
@@ -4832,7 +4818,7 @@ PHP_METHOD(DateInterval, __wakeup)
@@ -4924,7 +4910,7 @@ PHP_METHOD(DateInterval, createFromDateString)
/* {{{ date_interval_format - */
-static zend_string *date_interval_format(char *format, size_t format_len, timelib_rel_time *t)
+static zend_string *date_interval_format(const char *format, size_t format_len, timelib_rel_time *t)
@@ -4998,7 +4984,7 @@ PHP_FUNCTION(date_interval_format)
zval *object;
php_interval_obj *diobj;
- char *format;
size_t format_len;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) {
@@ -5011,7 +4997,7 @@ PHP_FUNCTION(date_interval_format)
-static bool date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, zend_long *recurrences, /*const*/ char *format, size_t format_length) /* {{{ */
+static bool date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, zend_long *recurrences, const char *format, size_t format_length) /* {{{ */
@@ -5044,7 +5030,7 @@ static bool date_period_initialize(timelib_time **st, timelib_time **et, timelib
return retval;
} /* }}} */
-static bool date_period_init_iso8601_string(php_period_obj *dpobj, zend_class_entry* base_ce, char *isostr, size_t isostr_len, zend_long options, zend_long *recurrences)
+static bool date_period_init_iso8601_string(php_period_obj *dpobj, zend_class_entry* base_ce, const char *isostr, size_t isostr_len, zend_long *recurrences)
if (!date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), recurrences, isostr, isostr_len)) {
return false;
@@ -5130,7 +5116,7 @@ PHP_METHOD(DatePeriod, createFromISO8601String)
dpobj->current = NULL;
- if (!date_period_init_iso8601_string(dpobj, date_ce_immutable, isostr, isostr_len, options, &recurrences)) {
+ if (!date_period_init_iso8601_string(dpobj, date_ce_immutable, isostr, isostr_len, &recurrences)) {
RETURN_THROWS();
}
@@ -5169,7 +5155,7 @@ PHP_METHOD(DatePeriod, __construct)
+ if (!date_period_init_iso8601_string(dpobj, date_ce_date, isostr, isostr_len, &recurrences)) {
} else {
@@ -5305,7 +5291,7 @@ PHP_METHOD(DatePeriod, getIterator)
zend_create_internal_iterator_zval(return_value, ZEND_THIS);
-static int check_id_allowed(char *id, zend_long what) /* {{{ */
if ((what & PHP_DATE_TIMEZONE_GROUP_AFRICA) && strncasecmp(id, "Africa/", 7) == 0) return 1;
if ((what & PHP_DATE_TIMEZONE_GROUP_AMERICA) && strncasecmp(id, "America/", 8) == 0) return 1;
@@ -5711,7 +5697,7 @@ static void date_period_object_to_hash(php_period_obj *period_obj, HashTable *pr
zend_hash_str_update(props, "include_end_date", sizeof("include_end_date")-1, &zv);
-static bool php_date_period_initialize_from_hash(php_period_obj *period_obj, HashTable *myht) /* {{{ */
zval *ht_entry;
@@ -5835,15 +5821,12 @@ static bool php_date_period_initialize_from_hash(php_period_obj *period_obj, Has
PHP_METHOD(DatePeriod, __set_state)
object_init_ex(return_value, date_ce_period);
period_obj = Z_PHPPERIOD_P(return_value);
@@ -5877,7 +5860,7 @@ PHP_METHOD(DatePeriod, __serialize)
* Common for date_period_read_property(), date_period_write_property(), and
* restore_custom_dateperiod_properties functions
*/
+static bool date_period_is_internal_property(const zend_string *name)
zend_string_equals_literal(name, "start") ||
@@ -5894,7 +5877,7 @@ static bool date_period_is_internal_property(zend_string *name)
-static void restore_custom_dateperiod_properties(zval *object, HashTable *myht)
+static void restore_custom_dateperiod_properties(zval *object, const HashTable *myht)
@@ -5912,15 +5895,13 @@ PHP_METHOD(DatePeriod, __unserialize)
period_obj = Z_PHPPERIOD_P(object);
zend_throw_error(NULL, "Invalid serialization data for DatePeriod object");
@@ -5935,7 +5916,7 @@ PHP_METHOD(DatePeriod, __wakeup)
diff --git a/ext/date/php_date.h b/ext/date/php_date.h
index f1b7c892001a9..f5f43bc7dfb0f 100644
--- a/ext/date/php_date.h
+++ b/ext/date/php_date.h
@@ -89,9 +89,9 @@ static inline php_timezone_obj *php_timezone_obj_from_obj(zend_object *obj) {
struct _php_interval_obj {
timelib_rel_time *diff;
int civil_or_wall;
+ bool initialized;
bool from_string;
zend_string *date_string;
- bool initialized;
zend_object std;
};
@@ -140,7 +140,7 @@ PHPAPI int php_idate(char format, time_t ts, bool localtime);
PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, bool gm);
PHPAPI zend_string *php_format_date(const char *format, size_t format_len, time_t ts, bool localtime);
-PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, php_date_obj *date_obj);
+PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, const php_date_obj *date_obj);
/* Mechanism to set new TZ database */
PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb); | [
"-PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, php_date_obj *date_obj)",
"-static void zval_from_error_container(zval *z, timelib_error_container *error) /* {{{ */",
"+static void zval_from_error_container(zval *z, const timelib_error_container *error) /* {{{ */",
"+static void set_timezone_from_timelib_time(php_timezone_obj *tzobj, const timelib_time *t)",
"+static bool php_date_timezone_initialize_from_hash(zval **return_value, php_timezone_obj **tzobj, const HashTable *myht) /* {{{ */",
"+static void restore_custom_datetimezone_properties(zval *object, const HashTable *myht)",
"+\tconst char *format;",
"-\t\tif (!date_period_init_iso8601_string(dpobj, date_ce_date, isostr, isostr_len, options, &recurrences)) {",
"+static bool check_id_allowed(const char *id, zend_long what) /* {{{ */",
"+static bool php_date_period_initialize_from_hash(php_period_obj *period_obj, const HashTable *myht) /* {{{ */",
"-static bool date_period_is_internal_property(zend_string *name)"
] | [
17,
96,
97,
106,
115,
159,
295,
330,
340,
349,
374
] | {
"additions": 41,
"author": "Girgias",
"deletions": 60,
"html_url": "https://github.com/php/php-src/pull/18044",
"issue_id": 18044,
"merged_at": "2025-03-28T16:55:37Z",
"omission_probability": 0.1,
"pr_number": 18044,
"repo": "php/php-src",
"title": "ext/date: Various minor refactorings",
"total_changes": 101
} |
781 | diff --git a/UPGRADING.INTERNALS b/UPGRADING.INTERNALS
index d2ab4e13fc52c..13b5e6a394434 100644
--- a/UPGRADING.INTERNALS
+++ b/UPGRADING.INTERNALS
@@ -21,6 +21,8 @@ PHP 8.5 INTERNALS UPGRADE NOTES
could interfere.
. zend_get_callable_name() now returns the name of the underlying function
for fake closures.
+ . Added smart_string_append_printf() matching smart_str_append_printf() for
+ char* instead of zend_string*-based smart strings.
========================
2. Build system changes
diff --git a/Zend/zend_smart_str.c b/Zend/zend_smart_str.c
index ade137a4bb6c3..501f6e6176c8b 100644
--- a/Zend/zend_smart_str.c
+++ b/Zend/zend_smart_str.c
@@ -131,6 +131,13 @@ ZEND_API void smart_str_append_printf(smart_str *dest, const char *format, ...)
va_end(arg);
}
+ZEND_API void smart_string_append_printf(smart_string *dest, const char *format, ...) {
+ va_list arg;
+ va_start(arg, format);
+ zend_printf_to_smart_string(dest, format, arg);
+ va_end(arg);
+}
+
#define SMART_STRING_OVERHEAD (ZEND_MM_OVERHEAD + 1)
#define SMART_STRING_START_SIZE 256
#define SMART_STRING_START_LEN (SMART_STRING_START_SIZE - SMART_STRING_OVERHEAD)
diff --git a/Zend/zend_smart_string.h b/Zend/zend_smart_string.h
index 8149b29fb3330..9f04e1a340ad2 100644
--- a/Zend/zend_smart_string.h
+++ b/Zend/zend_smart_string.h
@@ -48,6 +48,9 @@
#define smart_string_append_unsigned(str, val) \
smart_string_append_unsigned_ex((str), (val), 0)
+ZEND_API void smart_string_append_printf(smart_string *dest, const char *format, ...)
+ ZEND_ATTRIBUTE_FORMAT(printf, 2, 3);
+
ZEND_API void ZEND_FASTCALL _smart_string_alloc_persistent(smart_string *str, size_t len);
ZEND_API void ZEND_FASTCALL _smart_string_alloc(smart_string *str, size_t len);
| diff --git a/UPGRADING.INTERNALS b/UPGRADING.INTERNALS
index d2ab4e13fc52c..13b5e6a394434 100644
--- a/UPGRADING.INTERNALS
+++ b/UPGRADING.INTERNALS
@@ -21,6 +21,8 @@ PHP 8.5 INTERNALS UPGRADE NOTES
could interfere.
. zend_get_callable_name() now returns the name of the underlying function
for fake closures.
+ . Added smart_string_append_printf() matching smart_str_append_printf() for
+ char* instead of zend_string*-based smart strings.
========================
2. Build system changes
diff --git a/Zend/zend_smart_str.c b/Zend/zend_smart_str.c
index ade137a4bb6c3..501f6e6176c8b 100644
--- a/Zend/zend_smart_str.c
+++ b/Zend/zend_smart_str.c
@@ -131,6 +131,13 @@ ZEND_API void smart_str_append_printf(smart_str *dest, const char *format, ...)
va_end(arg);
}
+ZEND_API void smart_string_append_printf(smart_string *dest, const char *format, ...) {
+ va_list arg;
+ va_start(arg, format);
+ zend_printf_to_smart_string(dest, format, arg);
+}
#define SMART_STRING_OVERHEAD (ZEND_MM_OVERHEAD + 1)
#define SMART_STRING_START_SIZE 256
#define SMART_STRING_START_LEN (SMART_STRING_START_SIZE - SMART_STRING_OVERHEAD)
diff --git a/Zend/zend_smart_string.h b/Zend/zend_smart_string.h
index 8149b29fb3330..9f04e1a340ad2 100644
--- a/Zend/zend_smart_string.h
+++ b/Zend/zend_smart_string.h
@@ -48,6 +48,9 @@
#define smart_string_append_unsigned(str, val) \
smart_string_append_unsigned_ex((str), (val), 0)
+ZEND_API void smart_string_append_printf(smart_string *dest, const char *format, ...)
+ ZEND_ATTRIBUTE_FORMAT(printf, 2, 3);
ZEND_API void ZEND_FASTCALL _smart_string_alloc_persistent(smart_string *str, size_t len);
ZEND_API void ZEND_FASTCALL _smart_string_alloc(smart_string *str, size_t len); | [
"+\tva_end(arg);"
] | [
25
] | {
"additions": 12,
"author": "TimWolla",
"deletions": 0,
"html_url": "https://github.com/php/php-src/pull/18160",
"issue_id": 18160,
"merged_at": "2025-03-27T19:15:25Z",
"omission_probability": 0.1,
"pr_number": 18160,
"repo": "php/php-src",
"title": "zend_smart_string: Add `smart_string_append_printf()`",
"total_changes": 12
} |
782 | diff --git a/NEWS b/NEWS
index 285bf4e23a80d..dc464b1abecab 100644
--- a/NEWS
+++ b/NEWS
@@ -9,6 +9,8 @@ PHP NEWS
(ilutov)
. Fixed bug GH-17376 (Broken JIT polymorphism for property hooks added to
child class). (ilutov)
+ . Fixed bug GH-17913 (ReflectionFunction::isDeprecated() returns incorrect
+ results for closures created from magic __call()). (timwolla)
27 Feb 2025, PHP 8.4.5
diff --git a/Zend/zend_closures.c b/Zend/zend_closures.c
index 049c026845b1c..6ad2f6ac40246 100644
--- a/Zend/zend_closures.c
+++ b/Zend/zend_closures.c
@@ -361,11 +361,12 @@ static zend_result zend_create_closure_from_callable(zval *return_value, zval *c
memset(&call, 0, sizeof(zend_internal_function));
call.type = ZEND_INTERNAL_FUNCTION;
- call.fn_flags = mptr->common.fn_flags & ZEND_ACC_STATIC;
+ call.fn_flags = mptr->common.fn_flags & (ZEND_ACC_STATIC | ZEND_ACC_DEPRECATED);
call.handler = zend_closure_call_magic;
call.function_name = mptr->common.function_name;
call.scope = mptr->common.scope;
call.doc_comment = NULL;
+ call.attributes = mptr->common.attributes;
zend_free_trampoline(mptr);
mptr = (zend_function *) &call;
@@ -871,7 +872,7 @@ void zend_closure_from_frame(zval *return_value, zend_execute_data *call) { /* {
memset(&trampoline, 0, sizeof(zend_internal_function));
trampoline.type = ZEND_INTERNAL_FUNCTION;
- trampoline.fn_flags = mptr->common.fn_flags & (ZEND_ACC_STATIC | ZEND_ACC_VARIADIC | ZEND_ACC_RETURN_REFERENCE);
+ trampoline.fn_flags = mptr->common.fn_flags & (ZEND_ACC_STATIC | ZEND_ACC_VARIADIC | ZEND_ACC_RETURN_REFERENCE | ZEND_ACC_DEPRECATED);
trampoline.handler = zend_closure_call_magic;
trampoline.function_name = mptr->common.function_name;
trampoline.scope = mptr->common.scope;
@@ -879,6 +880,7 @@ void zend_closure_from_frame(zval *return_value, zend_execute_data *call) { /* {
if (trampoline.fn_flags & ZEND_ACC_VARIADIC) {
trampoline.arg_info = trampoline_arg_info;
}
+ trampoline.attributes = mptr->common.attributes;
zend_free_trampoline(mptr);
mptr = (zend_function *) &trampoline;
diff --git a/ext/reflection/tests/ReflectionFunction_isDeprecated_magic_call.phpt b/ext/reflection/tests/ReflectionFunction_isDeprecated_magic_call.phpt
new file mode 100644
index 0000000000000..fa63816c44ec7
--- /dev/null
+++ b/ext/reflection/tests/ReflectionFunction_isDeprecated_magic_call.phpt
@@ -0,0 +1,70 @@
+--TEST--
+GH-17913: ReflectionClassConstant::isDeprecated() with __call() and __callStatic()
+--FILE--
+<?php
+
+class Clazz {
+ #[\Deprecated]
+ function __call(string $name, array $params) {
+ }
+
+ #[\Deprecated("due to some reason")]
+ static function __callStatic(string $name, array $params) {
+ }
+}
+
+$foo = new Clazz;
+$closure = Closure::fromCallable([$foo, 'test']);
+
+$rc = new ReflectionFunction($closure);
+var_dump($rc->getAttributes()[0]->newInstance());
+var_dump($rc->isDeprecated());
+
+$closure = $foo->test(...);
+
+$rc = new ReflectionFunction($closure);
+var_dump($rc->getAttributes()[0]->newInstance());
+var_dump($rc->isDeprecated());
+
+$closure = Closure::fromCallable('Clazz::test');
+
+$rc = new ReflectionFunction($closure);
+var_dump($rc->getAttributes()[0]->newInstance());
+var_dump($rc->isDeprecated());
+
+$closure = Clazz::test(...);
+
+$rc = new ReflectionFunction($closure);
+var_dump($rc->getAttributes()[0]->newInstance());
+var_dump($rc->isDeprecated());
+
+?>
+--EXPECTF--
+object(Deprecated)#%d (2) {
+ ["message"]=>
+ NULL
+ ["since"]=>
+ NULL
+}
+bool(true)
+object(Deprecated)#%d (2) {
+ ["message"]=>
+ NULL
+ ["since"]=>
+ NULL
+}
+bool(true)
+object(Deprecated)#%d (2) {
+ ["message"]=>
+ string(18) "due to some reason"
+ ["since"]=>
+ NULL
+}
+bool(true)
+object(Deprecated)#%d (2) {
+ ["message"]=>
+ string(18) "due to some reason"
+ ["since"]=>
+ NULL
+}
+bool(true)
| diff --git a/NEWS b/NEWS
index 285bf4e23a80d..dc464b1abecab 100644
--- a/NEWS
+++ b/NEWS
@@ -9,6 +9,8 @@ PHP NEWS
(ilutov)
. Fixed bug GH-17376 (Broken JIT polymorphism for property hooks added to
child class). (ilutov)
+ . Fixed bug GH-17913 (ReflectionFunction::isDeprecated() returns incorrect
+ results for closures created from magic __call()). (timwolla)
27 Feb 2025, PHP 8.4.5
diff --git a/Zend/zend_closures.c b/Zend/zend_closures.c
index 049c026845b1c..6ad2f6ac40246 100644
--- a/Zend/zend_closures.c
+++ b/Zend/zend_closures.c
@@ -361,11 +361,12 @@ static zend_result zend_create_closure_from_callable(zval *return_value, zval *c
memset(&call, 0, sizeof(zend_internal_function));
call.type = ZEND_INTERNAL_FUNCTION;
- call.fn_flags = mptr->common.fn_flags & ZEND_ACC_STATIC;
call.handler = zend_closure_call_magic;
call.function_name = mptr->common.function_name;
call.scope = mptr->common.scope;
call.doc_comment = NULL;
+ call.attributes = mptr->common.attributes;
mptr = (zend_function *) &call;
@@ -871,7 +872,7 @@ void zend_closure_from_frame(zval *return_value, zend_execute_data *call) { /* {
memset(&trampoline, 0, sizeof(zend_internal_function));
trampoline.type = ZEND_INTERNAL_FUNCTION;
- trampoline.fn_flags = mptr->common.fn_flags & (ZEND_ACC_STATIC | ZEND_ACC_VARIADIC | ZEND_ACC_RETURN_REFERENCE);
+ trampoline.fn_flags = mptr->common.fn_flags & (ZEND_ACC_STATIC | ZEND_ACC_VARIADIC | ZEND_ACC_RETURN_REFERENCE | ZEND_ACC_DEPRECATED);
trampoline.handler = zend_closure_call_magic;
trampoline.function_name = mptr->common.function_name;
trampoline.scope = mptr->common.scope;
@@ -879,6 +880,7 @@ void zend_closure_from_frame(zval *return_value, zend_execute_data *call) { /* {
if (trampoline.fn_flags & ZEND_ACC_VARIADIC) {
trampoline.arg_info = trampoline_arg_info;
}
mptr = (zend_function *) &trampoline;
diff --git a/ext/reflection/tests/ReflectionFunction_isDeprecated_magic_call.phpt b/ext/reflection/tests/ReflectionFunction_isDeprecated_magic_call.phpt
new file mode 100644
index 0000000000000..fa63816c44ec7
--- /dev/null
+++ b/ext/reflection/tests/ReflectionFunction_isDeprecated_magic_call.phpt
@@ -0,0 +1,70 @@
+--TEST--
+GH-17913: ReflectionClassConstant::isDeprecated() with __call() and __callStatic()
+--FILE--
+<?php
+ #[\Deprecated]
+ function __call(string $name, array $params) {
+ #[\Deprecated("due to some reason")]
+ static function __callStatic(string $name, array $params) {
+$foo = new Clazz;
+$closure = Closure::fromCallable([$foo, 'test']);
+$closure = $foo->test(...);
+$closure = Closure::fromCallable('Clazz::test');
+$closure = Clazz::test(...);
+--EXPECTF-- | [
"+\t\tcall.fn_flags = mptr->common.fn_flags & (ZEND_ACC_STATIC | ZEND_ACC_DEPRECATED);",
"+\t\ttrampoline.attributes = mptr->common.attributes;",
"+class Clazz {",
"+?>"
] | [
22,
44,
59,
94
] | {
"additions": 76,
"author": "TimWolla",
"deletions": 2,
"html_url": "https://github.com/php/php-src/pull/17914",
"issue_id": 17914,
"merged_at": "2025-02-27T13:48:09Z",
"omission_probability": 0.1,
"pr_number": 17914,
"repo": "php/php-src",
"title": "Fix `ReflectionFunction::isDeprecated()` for materialized `__call()`",
"total_changes": 78
} |
783 | diff --git a/Zend/tests/closures/closure_const_expr/attributes.phpt b/Zend/tests/closures/closure_const_expr/attributes.phpt
index c83b821d12969..e331bc2edd568 100644
--- a/Zend/tests/closures/closure_const_expr/attributes.phpt
+++ b/Zend/tests/closures/closure_const_expr/attributes.phpt
@@ -8,13 +8,13 @@ reflection
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class Attr {
public function __construct(public Closure $value) {
- $value('foo');
+ $value('foo');
}
}
#[Attr(static function () { })]
#[Attr(static function (...$args) {
- var_dump($args);
+ var_dump($args);
})]
class C {}
diff --git a/Zend/tests/closures/closure_const_expr/attributes_autoload.inc b/Zend/tests/closures/closure_const_expr/attributes_autoload.inc
new file mode 100644
index 0000000000000..48f9b1987cf5d
--- /dev/null
+++ b/Zend/tests/closures/closure_const_expr/attributes_autoload.inc
@@ -0,0 +1,9 @@
+<?php
+
+#[Attr(static function () { })]
+#[Attr(static function (...$args) {
+ var_dump($args);
+})]
+class C {}
+
+?>
diff --git a/Zend/tests/closures/closure_const_expr/attributes_autoload.phpt b/Zend/tests/closures/closure_const_expr/attributes_autoload.phpt
new file mode 100644
index 0000000000000..fa99e8b5abaa3
--- /dev/null
+++ b/Zend/tests/closures/closure_const_expr/attributes_autoload.phpt
@@ -0,0 +1,57 @@
+--TEST--
+GH-17851: Use-after-free when instantiating autoloaded class with attribute having a Closure parameter.
+--EXTENSIONS--
+reflection
+--FILE--
+<?php
+
+spl_autoload_register(static function ($className) {
+ if ($className === 'C') {
+ require(__DIR__ . '/attributes_autoload.inc');
+ }
+});
+
+#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
+class Attr {
+ public function __construct(public Closure $value) {
+ $value('foo');
+ }
+}
+
+foreach ((new ReflectionClass(C::class))->getAttributes() as $reflectionAttribute) {
+ var_dump($reflectionAttribute->newInstance());
+}
+
+?>
+--EXPECTF--
+object(Attr)#%d (1) {
+ ["value"]=>
+ object(Closure)#%d (3) {
+ ["name"]=>
+ string(%d) "{closure:%s:%d}"
+ ["file"]=>
+ string(%d) "%s"
+ ["line"]=>
+ int(%d)
+ }
+}
+array(1) {
+ [0]=>
+ string(3) "foo"
+}
+object(Attr)#%d (1) {
+ ["value"]=>
+ object(Closure)#%d (4) {
+ ["name"]=>
+ string(%d) "{closure:%s:%d}"
+ ["file"]=>
+ string(%d) "%s"
+ ["line"]=>
+ int(%d)
+ ["parameter"]=>
+ array(1) {
+ ["$args"]=>
+ string(10) "<optional>"
+ }
+ }
+}
diff --git a/Zend/tests/closures/closure_const_expr/static_variable.phpt b/Zend/tests/closures/closure_const_expr/static_variable.phpt
new file mode 100644
index 0000000000000..5aea594d8620b
--- /dev/null
+++ b/Zend/tests/closures/closure_const_expr/static_variable.phpt
@@ -0,0 +1,77 @@
+--TEST--
+Closures in const expressions support static variables.
+--FILE--
+<?php
+
+const Closure = static function () {
+ static $x = [];
+ static $i = 1;
+ $i *= 2;
+ $x[] = $i;
+ var_dump($x);
+};
+
+var_dump(Closure);
+(Closure)();
+(Closure)();
+(Closure)();
+var_dump(Closure);
+
+?>
+--EXPECTF--
+object(Closure)#%d (4) {
+ ["name"]=>
+ string(%d) "{closure:%s:%d}"
+ ["file"]=>
+ string(%d) "%s"
+ ["line"]=>
+ int(3)
+ ["static"]=>
+ array(2) {
+ ["x"]=>
+ array(0) {
+ }
+ ["i"]=>
+ int(1)
+ }
+}
+array(1) {
+ [0]=>
+ int(2)
+}
+array(2) {
+ [0]=>
+ int(2)
+ [1]=>
+ int(4)
+}
+array(3) {
+ [0]=>
+ int(2)
+ [1]=>
+ int(4)
+ [2]=>
+ int(8)
+}
+object(Closure)#%d (4) {
+ ["name"]=>
+ string(%d) "{closure:%s:%d}"
+ ["file"]=>
+ string(%d) "%s"
+ ["line"]=>
+ int(3)
+ ["static"]=>
+ array(2) {
+ ["x"]=>
+ array(3) {
+ [0]=>
+ int(2)
+ [1]=>
+ int(4)
+ [2]=>
+ int(8)
+ }
+ ["i"]=>
+ int(8)
+ }
+}
diff --git a/Zend/zend_ast.c b/Zend/zend_ast.c
index 1ae7a0ef7a68e..2551f876d4465 100644
--- a/Zend/zend_ast.c
+++ b/Zend/zend_ast.c
@@ -1277,6 +1277,7 @@ static void* ZEND_FASTCALL zend_ast_tree_copy(zend_ast *ast, void *buf)
new->attr = old->attr;
new->lineno = old->lineno;
new->op_array = old->op_array;
+ function_add_ref((zend_function *)new->op_array);
buf = (void*)((char*)buf + sizeof(zend_ast_op_array));
} else if (ast->kind == ZEND_AST_CALLABLE_CONVERT) {
zend_ast_fcc *old = (zend_ast_fcc*)ast;
@@ -1353,7 +1354,7 @@ ZEND_API void ZEND_FASTCALL zend_ast_destroy(zend_ast *ast)
} else if (EXPECTED(ast->kind == ZEND_AST_CONSTANT)) {
zend_string_release_ex(zend_ast_get_constant_name(ast), 0);
} else if (EXPECTED(ast->kind == ZEND_AST_OP_ARRAY)) {
- /* Nothing to do. */
+ destroy_op_array(zend_ast_get_op_array(ast)->op_array);
} else if (EXPECTED(zend_ast_is_decl(ast))) {
zend_ast_decl *decl = (zend_ast_decl *) ast;
diff --git a/Zend/zend_closures.c b/Zend/zend_closures.c
index e9945b3284cd9..5777e1a34a2b8 100644
--- a/Zend/zend_closures.c
+++ b/Zend/zend_closures.c
@@ -528,7 +528,6 @@ static void zend_closure_free_storage(zend_object *object) /* {{{ */
/* We don't own the static variables of fake closures. */
if (!(closure->func.op_array.fn_flags & ZEND_ACC_FAKE_CLOSURE)) {
zend_destroy_static_vars(&closure->func.op_array);
- closure->func.op_array.static_variables = NULL;
}
destroy_op_array(&closure->func.op_array);
} else if (closure->func.type == ZEND_INTERNAL_FUNCTION) {
@@ -760,16 +759,14 @@ static void zend_create_closure_ex(zval *res, zend_function *func, zend_class_en
}
/* For fake closures, we want to reuse the static variables of the original function. */
+ HashTable *ht = ZEND_MAP_PTR_GET(func->op_array.static_variables_ptr);
if (!is_fake) {
- if (closure->func.op_array.static_variables) {
- closure->func.op_array.static_variables =
- zend_array_dup(closure->func.op_array.static_variables);
+ if (!ht) {
+ ht = closure->func.op_array.static_variables;
}
ZEND_MAP_PTR_INIT(closure->func.op_array.static_variables_ptr,
- closure->func.op_array.static_variables);
+ ht ? zend_array_dup(ht) : NULL);
} else if (func->op_array.static_variables) {
- HashTable *ht = ZEND_MAP_PTR_GET(func->op_array.static_variables_ptr);
-
if (!ht) {
ht = zend_array_dup(func->op_array.static_variables);
ZEND_MAP_PTR_SET(func->op_array.static_variables_ptr, ht);
diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c
index 1cba9ef221997..c2724955f17b8 100644
--- a/Zend/zend_compile.c
+++ b/Zend/zend_compile.c
@@ -8244,9 +8244,6 @@ static zend_string *zend_begin_func_decl(znode *result, zend_op_array *op_array,
zend_register_seen_symbol(lcname, ZEND_SYMBOL_FUNCTION);
switch (level) {
- case FUNC_DECL_LEVEL_CONSTEXPR:
- zend_add_dynamic_func_def(op_array);
- break;
case FUNC_DECL_LEVEL_NESTED: {
uint32_t func_ref = zend_add_dynamic_func_def(op_array);
if (op_array->fn_flags & ZEND_ACC_CLOSURE) {
@@ -8261,6 +8258,7 @@ static zend_string *zend_begin_func_decl(znode *result, zend_op_array *op_array,
}
break;
}
+ case FUNC_DECL_LEVEL_CONSTEXPR:
case FUNC_DECL_LEVEL_TOPLEVEL:
/* Nothing to do. */
break;
diff --git a/Zend/zend_opcode.c b/Zend/zend_opcode.c
index f32ae13e06793..ce052024ae7a0 100644
--- a/Zend/zend_opcode.c
+++ b/Zend/zend_opcode.c
@@ -636,13 +636,6 @@ ZEND_API void destroy_op_array(zend_op_array *op_array)
}
if (op_array->num_dynamic_func_defs) {
for (i = 0; i < op_array->num_dynamic_func_defs; i++) {
- /* Closures overwrite static_variables in their copy.
- * Make sure to destroy them when the prototype function is destroyed. */
- if (op_array->dynamic_func_defs[i]->static_variables
- && (op_array->dynamic_func_defs[i]->fn_flags & ZEND_ACC_CLOSURE)) {
- zend_array_destroy(op_array->dynamic_func_defs[i]->static_variables);
- op_array->dynamic_func_defs[i]->static_variables = NULL;
- }
destroy_op_array(op_array->dynamic_func_defs[i]);
}
efree(op_array->dynamic_func_defs);
diff --git a/ext/opcache/zend_file_cache.c b/ext/opcache/zend_file_cache.c
index e612dcd80748b..a2346a56d458e 100644
--- a/ext/opcache/zend_file_cache.c
+++ b/ext/opcache/zend_file_cache.c
@@ -242,6 +242,15 @@ static void zend_file_cache_unserialize_zval(zval *zv,
zend_persistent_script *script,
void *buf);
+static void zend_file_cache_serialize_func(zval *zv,
+ zend_persistent_script *script,
+ zend_file_cache_metainfo *info,
+ void *buf);
+
+static void zend_file_cache_unserialize_func(zval *zv,
+ zend_persistent_script *script,
+ void *buf);
+
static void *zend_file_cache_serialize_interned(zend_string *str,
zend_file_cache_metainfo *info)
{
@@ -364,8 +373,10 @@ static void zend_file_cache_serialize_ast(zend_ast *ast,
}
}
} else if (ast->kind == ZEND_AST_OP_ARRAY) {
- /* The op_array itself will be serialized as part of the dynamic_func_defs. */
- SERIALIZE_PTR(zend_ast_get_op_array(ast)->op_array);
+ zval z;
+ ZVAL_PTR(&z, zend_ast_get_op_array(ast)->op_array);
+ zend_file_cache_serialize_func(&z, script, info, buf);
+ zend_ast_get_op_array(ast)->op_array = Z_PTR(z);
} else if (ast->kind == ZEND_AST_CALLABLE_CONVERT) {
zend_ast_fcc *fcc = (zend_ast_fcc*)ast;
ZEND_MAP_PTR_INIT(fcc->fptr, NULL);
@@ -1252,8 +1263,10 @@ static void zend_file_cache_unserialize_ast(zend_ast *ast,
}
}
} else if (ast->kind == ZEND_AST_OP_ARRAY) {
- /* The op_array itself will be unserialized as part of the dynamic_func_defs. */
- UNSERIALIZE_PTR(zend_ast_get_op_array(ast)->op_array);
+ zval z;
+ ZVAL_PTR(&z, zend_ast_get_op_array(ast)->op_array);
+ zend_file_cache_unserialize_func(&z, script, buf);
+ zend_ast_get_op_array(ast)->op_array = Z_PTR(z);
} else if (ast->kind == ZEND_AST_CALLABLE_CONVERT) {
zend_ast_fcc *fcc = (zend_ast_fcc*)ast;
ZEND_MAP_PTR_NEW(fcc->fptr);
| diff --git a/Zend/tests/closures/closure_const_expr/attributes.phpt b/Zend/tests/closures/closure_const_expr/attributes.phpt
index c83b821d12969..e331bc2edd568 100644
--- a/Zend/tests/closures/closure_const_expr/attributes.phpt
+++ b/Zend/tests/closures/closure_const_expr/attributes.phpt
@@ -8,13 +8,13 @@ reflection
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class Attr {
public function __construct(public Closure $value) {
- $value('foo');
}
}
#[Attr(static function () { })]
#[Attr(static function (...$args) {
- var_dump($args);
})]
class C {}
diff --git a/Zend/tests/closures/closure_const_expr/attributes_autoload.inc b/Zend/tests/closures/closure_const_expr/attributes_autoload.inc
index 0000000000000..48f9b1987cf5d
+++ b/Zend/tests/closures/closure_const_expr/attributes_autoload.inc
@@ -0,0 +1,9 @@
+#[Attr(static function () { })]
+})]
+class C {}
diff --git a/Zend/tests/closures/closure_const_expr/attributes_autoload.phpt b/Zend/tests/closures/closure_const_expr/attributes_autoload.phpt
index 0000000000000..fa99e8b5abaa3
+++ b/Zend/tests/closures/closure_const_expr/attributes_autoload.phpt
@@ -0,0 +1,57 @@
+GH-17851: Use-after-free when instantiating autoloaded class with attribute having a Closure parameter.
+--EXTENSIONS--
+reflection
+spl_autoload_register(static function ($className) {
+ if ($className === 'C') {
+ require(__DIR__ . '/attributes_autoload.inc');
+});
+#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
+class Attr {
+ public function __construct(public Closure $value) {
+foreach ((new ReflectionClass(C::class))->getAttributes() as $reflectionAttribute) {
+ var_dump($reflectionAttribute->newInstance());
+ string(3) "foo"
+ object(Closure)#%d (4) {
+ ["parameter"]=>
+ array(1) {
+ ["$args"]=>
+ string(10) "<optional>"
diff --git a/Zend/tests/closures/closure_const_expr/static_variable.phpt b/Zend/tests/closures/closure_const_expr/static_variable.phpt
index 0000000000000..5aea594d8620b
+++ b/Zend/tests/closures/closure_const_expr/static_variable.phpt
@@ -0,0 +1,77 @@
+Closures in const expressions support static variables.
+const Closure = static function () {
+ static $x = [];
+ static $i = 1;
+ $i *= 2;
+ $x[] = $i;
+ var_dump($x);
+};
+ array(0) {
+ int(1)
+array(3) {
+ [2]=>
+ int(8)
+ [0]=>
+ int(2)
+ [1]=>
+ int(4)
+ int(8)
+ int(8)
diff --git a/Zend/zend_ast.c b/Zend/zend_ast.c
index 1ae7a0ef7a68e..2551f876d4465 100644
--- a/Zend/zend_ast.c
+++ b/Zend/zend_ast.c
@@ -1277,6 +1277,7 @@ static void* ZEND_FASTCALL zend_ast_tree_copy(zend_ast *ast, void *buf)
new->attr = old->attr;
new->lineno = old->lineno;
new->op_array = old->op_array;
+ function_add_ref((zend_function *)new->op_array);
buf = (void*)((char*)buf + sizeof(zend_ast_op_array));
zend_ast_fcc *old = (zend_ast_fcc*)ast;
@@ -1353,7 +1354,7 @@ ZEND_API void ZEND_FASTCALL zend_ast_destroy(zend_ast *ast)
} else if (EXPECTED(ast->kind == ZEND_AST_CONSTANT)) {
zend_string_release_ex(zend_ast_get_constant_name(ast), 0);
} else if (EXPECTED(ast->kind == ZEND_AST_OP_ARRAY)) {
- /* Nothing to do. */
+ destroy_op_array(zend_ast_get_op_array(ast)->op_array);
} else if (EXPECTED(zend_ast_is_decl(ast))) {
zend_ast_decl *decl = (zend_ast_decl *) ast;
diff --git a/Zend/zend_closures.c b/Zend/zend_closures.c
index e9945b3284cd9..5777e1a34a2b8 100644
--- a/Zend/zend_closures.c
+++ b/Zend/zend_closures.c
@@ -528,7 +528,6 @@ static void zend_closure_free_storage(zend_object *object) /* {{{ */
/* We don't own the static variables of fake closures. */
if (!(closure->func.op_array.fn_flags & ZEND_ACC_FAKE_CLOSURE)) {
zend_destroy_static_vars(&closure->func.op_array);
- closure->func.op_array.static_variables = NULL;
destroy_op_array(&closure->func.op_array);
} else if (closure->func.type == ZEND_INTERNAL_FUNCTION) {
@@ -760,16 +759,14 @@ static void zend_create_closure_ex(zval *res, zend_function *func, zend_class_en
/* For fake closures, we want to reuse the static variables of the original function. */
+ HashTable *ht = ZEND_MAP_PTR_GET(func->op_array.static_variables_ptr);
if (!is_fake) {
- if (closure->func.op_array.static_variables) {
- closure->func.op_array.static_variables =
- zend_array_dup(closure->func.op_array.static_variables);
+ if (!ht) {
+ ht = closure->func.op_array.static_variables;
ZEND_MAP_PTR_INIT(closure->func.op_array.static_variables_ptr,
- closure->func.op_array.static_variables);
+ ht ? zend_array_dup(ht) : NULL);
} else if (func->op_array.static_variables) {
- HashTable *ht = ZEND_MAP_PTR_GET(func->op_array.static_variables_ptr);
-
if (!ht) {
ht = zend_array_dup(func->op_array.static_variables);
ZEND_MAP_PTR_SET(func->op_array.static_variables_ptr, ht);
diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c
index 1cba9ef221997..c2724955f17b8 100644
--- a/Zend/zend_compile.c
+++ b/Zend/zend_compile.c
@@ -8244,9 +8244,6 @@ static zend_string *zend_begin_func_decl(znode *result, zend_op_array *op_array,
zend_register_seen_symbol(lcname, ZEND_SYMBOL_FUNCTION);
switch (level) {
- case FUNC_DECL_LEVEL_CONSTEXPR:
- zend_add_dynamic_func_def(op_array);
- break;
case FUNC_DECL_LEVEL_NESTED: {
uint32_t func_ref = zend_add_dynamic_func_def(op_array);
if (op_array->fn_flags & ZEND_ACC_CLOSURE) {
@@ -8261,6 +8258,7 @@ static zend_string *zend_begin_func_decl(znode *result, zend_op_array *op_array,
case FUNC_DECL_LEVEL_TOPLEVEL:
/* Nothing to do. */
diff --git a/Zend/zend_opcode.c b/Zend/zend_opcode.c
index f32ae13e06793..ce052024ae7a0 100644
--- a/Zend/zend_opcode.c
+++ b/Zend/zend_opcode.c
@@ -636,13 +636,6 @@ ZEND_API void destroy_op_array(zend_op_array *op_array)
}
if (op_array->num_dynamic_func_defs) {
for (i = 0; i < op_array->num_dynamic_func_defs; i++) {
- /* Closures overwrite static_variables in their copy.
- * Make sure to destroy them when the prototype function is destroyed. */
- if (op_array->dynamic_func_defs[i]->static_variables
- && (op_array->dynamic_func_defs[i]->fn_flags & ZEND_ACC_CLOSURE)) {
- zend_array_destroy(op_array->dynamic_func_defs[i]->static_variables);
- }
destroy_op_array(op_array->dynamic_func_defs[i]);
efree(op_array->dynamic_func_defs);
diff --git a/ext/opcache/zend_file_cache.c b/ext/opcache/zend_file_cache.c
index e612dcd80748b..a2346a56d458e 100644
--- a/ext/opcache/zend_file_cache.c
+++ b/ext/opcache/zend_file_cache.c
@@ -242,6 +242,15 @@ static void zend_file_cache_unserialize_zval(zval *zv,
zend_persistent_script *script,
void *buf);
+static void zend_file_cache_serialize_func(zval *zv,
+ zend_persistent_script *script,
+ zend_file_cache_metainfo *info,
+ void *buf);
+static void zend_file_cache_unserialize_func(zval *zv,
+ zend_persistent_script *script,
+ void *buf);
static void *zend_file_cache_serialize_interned(zend_string *str,
zend_file_cache_metainfo *info)
{
@@ -364,8 +373,10 @@ static void zend_file_cache_serialize_ast(zend_ast *ast,
- /* The op_array itself will be serialized as part of the dynamic_func_defs. */
- SERIALIZE_PTR(zend_ast_get_op_array(ast)->op_array);
+ zend_file_cache_serialize_func(&z, script, info, buf);
ZEND_MAP_PTR_INIT(fcc->fptr, NULL);
@@ -1252,8 +1263,10 @@ static void zend_file_cache_unserialize_ast(zend_ast *ast,
- /* The op_array itself will be unserialized as part of the dynamic_func_defs. */
- UNSERIALIZE_PTR(zend_ast_get_op_array(ast)->op_array);
+ zend_file_cache_unserialize_func(&z, script, buf);
ZEND_MAP_PTR_NEW(fcc->fptr); | [
"+#[Attr(static function (...$args) {",
"+ object(Closure)#%d (3) {",
"+array(2) {",
"+ array(3) {",
"+ [2]=>",
"+\t\tcase FUNC_DECL_LEVEL_CONSTEXPR:",
"-\t\t\t\top_array->dynamic_func_defs[i]->static_variables = NULL;"
] | [
29,
69,
145,
169,
174,
253,
270
] | {
"additions": 169,
"author": "TimWolla",
"deletions": 24,
"html_url": "https://github.com/php/php-src/pull/17853",
"issue_id": 17853,
"merged_at": "2025-03-27T09:11:45Z",
"omission_probability": 0.1,
"pr_number": 17853,
"repo": "php/php-src",
"title": "Zend: Fix reference counting for Closures in const-expr",
"total_changes": 193
} |
784 | diff --git a/ext/reflection/php_reflection.c b/ext/reflection/php_reflection.c
index 7aedca43d02ce..5fc4bd6b643b5 100644
--- a/ext/reflection/php_reflection.c
+++ b/ext/reflection/php_reflection.c
@@ -336,40 +336,40 @@ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, const
}
smart_str_append_printf(str, "%s%s [ ", indent, kind);
}
- smart_str_append_printf(str, (ce->type == ZEND_USER_CLASS) ? "<user" : "<internal");
+ smart_str_appends(str, (ce->type == ZEND_USER_CLASS) ? "<user" : "<internal");
if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module) {
smart_str_append_printf(str, ":%s", ce->info.internal.module->name);
}
- smart_str_append_printf(str, "> ");
+ smart_str_appends(str, "> ");
if (ce->get_iterator != NULL) {
- smart_str_append_printf(str, "<iterateable> ");
+ smart_str_appends(str, "<iterateable> ");
}
if (ce->ce_flags & ZEND_ACC_INTERFACE) {
- smart_str_append_printf(str, "interface ");
+ smart_str_appends(str, "interface ");
} else if (ce->ce_flags & ZEND_ACC_TRAIT) {
- smart_str_append_printf(str, "trait ");
+ smart_str_appends(str, "trait ");
} else if (ce->ce_flags & ZEND_ACC_ENUM) {
- smart_str_append_printf(str, "enum ");
+ smart_str_appends(str, "enum ");
} else {
if (ce->ce_flags & (ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) {
- smart_str_append_printf(str, "abstract ");
+ smart_str_appends(str, "abstract ");
}
if (ce->ce_flags & ZEND_ACC_FINAL) {
- smart_str_append_printf(str, "final ");
+ smart_str_appends(str, "final ");
}
if (ce->ce_flags & ZEND_ACC_READONLY_CLASS) {
- smart_str_append_printf(str, "readonly ");
+ smart_str_appends(str, "readonly ");
}
- smart_str_append_printf(str, "class ");
+ smart_str_appends(str, "class ");
}
- smart_str_append_printf(str, "%s", ZSTR_VAL(ce->name));
+ smart_str_append(str, ce->name);
if (ce->parent) {
smart_str_append_printf(str, " extends %s", ZSTR_VAL(ce->parent->name));
}
// Show backing type of enums
if ((ce->ce_flags & ZEND_ACC_ENUM) && (ce->enum_backing_type != IS_UNDEF)) {
- smart_str_append_printf(str,
+ smart_str_appends(str,
ce->enum_backing_type == IS_STRING ? ": string" : ": int"
);
}
@@ -386,7 +386,7 @@ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, const
smart_str_append_printf(str, ", %s", ZSTR_VAL(ce->interfaces[i]->name));
}
}
- smart_str_append_printf(str, " ] {\n");
+ smart_str_appends(str, " ] {\n");
/* The information where a class is declared is only available for user classes */
if (ce->type == ZEND_USER_CLASS) {
@@ -490,12 +490,12 @@ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, const
if ((mptr->common.fn_flags & ZEND_ACC_STATIC)
&& ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce))
{
- smart_str_append_printf(str, "\n");
+ smart_str_appendc(str, '\n');
_function_string(str, mptr, ce, ZSTR_VAL(sub_indent));
}
} ZEND_HASH_FOREACH_END();
} else {
- smart_str_append_printf(str, "\n");
+ smart_str_appendc(str, '\n');
}
smart_str_append_printf(str, "%s }\n", indent);
@@ -566,7 +566,7 @@ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, const
smart_str_append_printf(str, "\n%s - Methods [%d] {", indent, count);
smart_str_append_smart_str(str, &method_str);
if (!count) {
- smart_str_append_printf(str, "\n");
+ smart_str_appendc(str, '\n');
}
smart_str_free(&method_str);
} else {
@@ -590,7 +590,7 @@ static void _const_string(smart_str *str, const char *name, zval *value, const c
if (flags & (CONST_PERSISTENT|CONST_NO_FILE_CACHE|CONST_DEPRECATED)) {
bool first = true;
- smart_str_appends(str, "<");
+ smart_str_appendc(str, '<');
#define DUMP_CONST_FLAG(flag, output) \
do { \
@@ -754,7 +754,7 @@ static int format_default_value(smart_str *str, zval *value) {
ZEND_ASSERT(!(class->ce_flags & ZEND_ACC_ENUM));
smart_str_appends(str, "object(");
smart_str_append(str, class->name);
- smart_str_appends(str, ")");
+ smart_str_appendc(str, ')');
} else {
ZEND_ASSERT(Z_TYPE_P(value) == IS_CONSTANT_AST);
zend_string *ast_str = zend_ast_export("", Z_ASTVAL_P(value), "");
@@ -774,9 +774,9 @@ static void _parameter_string(smart_str *str, zend_function *fptr, struct _zend_
{
smart_str_append_printf(str, "Parameter #%d [ ", offset);
if (!required) {
- smart_str_append_printf(str, "<optional> ");
+ smart_str_appends(str, "<optional> ");
} else {
- smart_str_append_printf(str, "<required> ");
+ smart_str_appends(str, "<required> ");
}
if (ZEND_TYPE_IS_SET(arg_info->type)) {
zend_string *type_str = zend_type_to_string(arg_info->type);
@@ -862,7 +862,7 @@ static void _function_closure_string(smart_str *str, const zend_function *fptr,
return;
}
- smart_str_append_printf(str, "\n");
+ smart_str_appendc(str, '\n');
smart_str_append_printf(str, "%s- Bound Variables [%u] {\n", indent, count);
i = 0;
ZEND_HASH_MAP_FOREACH_STR_KEY(static_variables, key) {
@@ -890,8 +890,8 @@ static void _function_string(smart_str *str, zend_function *fptr, zend_class_ent
}
smart_str_appendl(str, indent, strlen(indent));
- smart_str_append_printf(str, fptr->common.fn_flags & ZEND_ACC_CLOSURE ? "Closure [ " : (fptr->common.scope ? "Method [ " : "Function [ "));
- smart_str_append_printf(str, (fptr->type == ZEND_USER_FUNCTION) ? "<user" : "<internal");
+ smart_str_appends(str, fptr->common.fn_flags & ZEND_ACC_CLOSURE ? "Closure [ " : (fptr->common.scope ? "Method [ " : "Function [ "));
+ smart_str_appends(str, (fptr->type == ZEND_USER_FUNCTION) ? "<user" : "<internal");
if (fptr->common.fn_flags & ZEND_ACC_DEPRECATED) {
smart_str_appends(str, ", deprecated");
}
@@ -1102,7 +1102,7 @@ static void _extension_class_string(zend_class_entry *ce, zend_string *key, smar
if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module && !strcasecmp(ce->info.internal.module->name, module->name)) {
/* dump class if it is not an alias */
if (zend_string_equals_ci(ce->name, key)) {
- smart_str_append_printf(str, "\n");
+ smart_str_appendc(str, '\n');
_class_string(str, ce, NULL, indent);
(*num_classes)++;
}
@@ -1165,7 +1165,7 @@ static void _extension_string(smart_str *str, const zend_module_entry *module, c
_extension_ini_string(ini_entry, &str_ini, indent, module->module_number);
} ZEND_HASH_FOREACH_END();
if (smart_str_get_len(&str_ini) > 0) {
- smart_str_append_printf(str, "\n - INI {\n");
+ smart_str_appends(str, "\n - INI {\n");
smart_str_append_smart_str(str, &str_ini);
smart_str_append_printf(str, "%s }\n", indent);
}
@@ -1200,7 +1200,7 @@ static void _extension_string(smart_str *str, const zend_module_entry *module, c
if (fptr->common.type==ZEND_INTERNAL_FUNCTION
&& fptr->internal_function.module == module) {
if (first) {
- smart_str_append_printf(str, "\n - Functions {\n");
+ smart_str_appends(str, "\n - Functions {\n");
first = 0;
}
_function_string(str, fptr, NULL, " ");
| diff --git a/ext/reflection/php_reflection.c b/ext/reflection/php_reflection.c
index 7aedca43d02ce..5fc4bd6b643b5 100644
--- a/ext/reflection/php_reflection.c
+++ b/ext/reflection/php_reflection.c
@@ -336,40 +336,40 @@ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, const
smart_str_append_printf(str, "%s%s [ ", indent, kind);
- smart_str_append_printf(str, (ce->type == ZEND_USER_CLASS) ? "<user" : "<internal");
+ smart_str_appends(str, (ce->type == ZEND_USER_CLASS) ? "<user" : "<internal");
if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module) {
smart_str_append_printf(str, ":%s", ce->info.internal.module->name);
- smart_str_append_printf(str, "> ");
+ smart_str_appends(str, "> ");
if (ce->get_iterator != NULL) {
- smart_str_append_printf(str, "<iterateable> ");
+ smart_str_appends(str, "<iterateable> ");
if (ce->ce_flags & ZEND_ACC_INTERFACE) {
- smart_str_append_printf(str, "interface ");
+ smart_str_appends(str, "interface ");
} else if (ce->ce_flags & ZEND_ACC_TRAIT) {
- smart_str_append_printf(str, "trait ");
} else if (ce->ce_flags & ZEND_ACC_ENUM) {
- smart_str_append_printf(str, "enum ");
+ smart_str_appends(str, "enum ");
if (ce->ce_flags & (ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) {
- smart_str_append_printf(str, "abstract ");
+ smart_str_appends(str, "abstract ");
if (ce->ce_flags & ZEND_ACC_FINAL) {
- smart_str_append_printf(str, "final ");
if (ce->ce_flags & ZEND_ACC_READONLY_CLASS) {
- smart_str_append_printf(str, "readonly ");
+ smart_str_appends(str, "class ");
- smart_str_append_printf(str, "%s", ZSTR_VAL(ce->name));
+ smart_str_append(str, ce->name);
if (ce->parent) {
smart_str_append_printf(str, " extends %s", ZSTR_VAL(ce->parent->name));
// Show backing type of enums
if ((ce->ce_flags & ZEND_ACC_ENUM) && (ce->enum_backing_type != IS_UNDEF)) {
- smart_str_append_printf(str,
+ smart_str_appends(str,
ce->enum_backing_type == IS_STRING ? ": string" : ": int"
);
@@ -386,7 +386,7 @@ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, const
smart_str_append_printf(str, ", %s", ZSTR_VAL(ce->interfaces[i]->name));
- smart_str_append_printf(str, " ] {\n");
+ smart_str_appends(str, " ] {\n");
/* The information where a class is declared is only available for user classes */
if (ce->type == ZEND_USER_CLASS) {
@@ -490,12 +490,12 @@ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, const
if ((mptr->common.fn_flags & ZEND_ACC_STATIC)
&& ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce))
{
- smart_str_append_printf(str, "\n");
+ smart_str_appendc(str, '\n');
_function_string(str, mptr, ce, ZSTR_VAL(sub_indent));
}
- smart_str_append_printf(str, "\n");
+ smart_str_appendc(str, '\n');
smart_str_append_printf(str, "%s }\n", indent);
@@ -566,7 +566,7 @@ static void _class_string(smart_str *str, zend_class_entry *ce, zval *obj, const
smart_str_append_printf(str, "\n%s - Methods [%d] {", indent, count);
smart_str_append_smart_str(str, &method_str);
if (!count) {
smart_str_free(&method_str);
@@ -590,7 +590,7 @@ static void _const_string(smart_str *str, const char *name, zval *value, const c
if (flags & (CONST_PERSISTENT|CONST_NO_FILE_CACHE|CONST_DEPRECATED)) {
bool first = true;
- smart_str_appends(str, "<");
+ smart_str_appendc(str, '<');
#define DUMP_CONST_FLAG(flag, output) \
do { \
@@ -754,7 +754,7 @@ static int format_default_value(smart_str *str, zval *value) {
ZEND_ASSERT(!(class->ce_flags & ZEND_ACC_ENUM));
smart_str_appends(str, "object(");
smart_str_append(str, class->name);
- smart_str_appends(str, ")");
+ smart_str_appendc(str, ')');
ZEND_ASSERT(Z_TYPE_P(value) == IS_CONSTANT_AST);
zend_string *ast_str = zend_ast_export("", Z_ASTVAL_P(value), "");
@@ -774,9 +774,9 @@ static void _parameter_string(smart_str *str, zend_function *fptr, struct _zend_
{
smart_str_append_printf(str, "Parameter #%d [ ", offset);
if (!required) {
- smart_str_append_printf(str, "<optional> ");
+ smart_str_appends(str, "<optional> ");
- smart_str_append_printf(str, "<required> ");
+ smart_str_appends(str, "<required> ");
if (ZEND_TYPE_IS_SET(arg_info->type)) {
zend_string *type_str = zend_type_to_string(arg_info->type);
@@ -862,7 +862,7 @@ static void _function_closure_string(smart_str *str, const zend_function *fptr,
return;
- smart_str_append_printf(str, "\n");
+ smart_str_appendc(str, '\n');
smart_str_append_printf(str, "%s- Bound Variables [%u] {\n", indent, count);
i = 0;
ZEND_HASH_MAP_FOREACH_STR_KEY(static_variables, key) {
@@ -890,8 +890,8 @@ static void _function_string(smart_str *str, zend_function *fptr, zend_class_ent
smart_str_appendl(str, indent, strlen(indent));
- smart_str_append_printf(str, fptr->common.fn_flags & ZEND_ACC_CLOSURE ? "Closure [ " : (fptr->common.scope ? "Method [ " : "Function [ "));
- smart_str_append_printf(str, (fptr->type == ZEND_USER_FUNCTION) ? "<user" : "<internal");
+ smart_str_appends(str, fptr->common.fn_flags & ZEND_ACC_CLOSURE ? "Closure [ " : (fptr->common.scope ? "Method [ " : "Function [ "));
+ smart_str_appends(str, (fptr->type == ZEND_USER_FUNCTION) ? "<user" : "<internal");
if (fptr->common.fn_flags & ZEND_ACC_DEPRECATED) {
smart_str_appends(str, ", deprecated");
@@ -1102,7 +1102,7 @@ static void _extension_class_string(zend_class_entry *ce, zend_string *key, smar
if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module && !strcasecmp(ce->info.internal.module->name, module->name)) {
/* dump class if it is not an alias */
if (zend_string_equals_ci(ce->name, key)) {
_class_string(str, ce, NULL, indent);
(*num_classes)++;
@@ -1165,7 +1165,7 @@ static void _extension_string(smart_str *str, const zend_module_entry *module, c
_extension_ini_string(ini_entry, &str_ini, indent, module->module_number);
if (smart_str_get_len(&str_ini) > 0) {
- smart_str_append_printf(str, "\n - INI {\n");
smart_str_append_smart_str(str, &str_ini);
smart_str_append_printf(str, "%s }\n", indent);
@@ -1200,7 +1200,7 @@ static void _extension_string(smart_str *str, const zend_module_entry *module, c
if (fptr->common.type==ZEND_INTERNAL_FUNCTION
&& fptr->internal_function.module == module) {
if (first) {
- smart_str_append_printf(str, "\n - Functions {\n");
+ smart_str_appends(str, "\n - Functions {\n");
first = 0;
}
_function_string(str, fptr, NULL, " "); | [
"+\t\tsmart_str_appends(str, \"trait \");",
"+\t\t\tsmart_str_appends(str, \"final \");",
"+\t\t\tsmart_str_appends(str, \"readonly \");",
"-\t\tsmart_str_append_printf(str, \"class \");",
"+\t\t\tsmart_str_appends(str, \"\\n - INI {\\n\");"
] | [
24,
35,
39,
41,
154
] | {
"additions": 26,
"author": "DanielEScherzer",
"deletions": 26,
"html_url": "https://github.com/php/php-src/pull/18155",
"issue_id": 18155,
"merged_at": "2025-03-26T23:00:34Z",
"omission_probability": 0.1,
"pr_number": 18155,
"repo": "php/php-src",
"title": "Reflection: optimize smart_str building",
"total_changes": 52
} |
785 | diff --git a/ext/bcmath/libbcmath/src/convert.c b/ext/bcmath/libbcmath/src/convert.c
index bf3d9a9a415bf..5438b4c1c44e5 100644
--- a/ext/bcmath/libbcmath/src/convert.c
+++ b/ext/bcmath/libbcmath/src/convert.c
@@ -17,24 +17,22 @@
#include "bcmath.h"
#include "convert.h"
#include "private.h"
-#ifdef __SSE2__
-# include <emmintrin.h>
-#endif
+#include "simd.h"
char *bc_copy_and_toggle_bcd(char *restrict dest, const char *source, const char *source_end)
{
const size_t bulk_shift = SWAR_REPEAT('0');
-#ifdef __SSE2__
- /* SIMD SSE2 bulk shift + copy */
- __m128i shift_vector = _mm_set1_epi8('0');
- while (source + sizeof(__m128i) <= source_end) {
- __m128i bytes = _mm_loadu_si128((const __m128i *) source);
- bytes = _mm_xor_si128(bytes, shift_vector);
- _mm_storeu_si128((__m128i *) dest, bytes);
+#ifdef HAVE_BC_SIMD_128
+ /* SIMD SSE2 or NEON bulk shift + copy */
+ bc_simd_128_t shift_vector = bc_simd_set_8x16('0');
+ while (source + sizeof(bc_simd_128_t) <= source_end) {
+ bc_simd_128_t bytes = bc_simd_load_8x16((const bc_simd_128_t *) source);
+ bytes = bc_simd_xor_8x16(bytes, shift_vector);
+ bc_simd_store_8x16((bc_simd_128_t *) dest, bytes);
- source += sizeof(__m128i);
- dest += sizeof(__m128i);
+ source += sizeof(bc_simd_128_t);
+ dest += sizeof(bc_simd_128_t);
}
#endif
diff --git a/ext/bcmath/libbcmath/src/simd.h b/ext/bcmath/libbcmath/src/simd.h
new file mode 100644
index 0000000000000..af38f8349618c
--- /dev/null
+++ b/ext/bcmath/libbcmath/src/simd.h
@@ -0,0 +1,59 @@
+/*
+ +----------------------------------------------------------------------+
+ | Copyright (c) The PHP Group |
+ +----------------------------------------------------------------------+
+ | This source file is subject to version 3.01 of the PHP license, |
+ | that is bundled with this package in the file LICENSE, and is |
+ | available through the world-wide-web at the following url: |
+ | https://www.php.net/license/3_01.txt |
+ | If you did not receive a copy of the PHP license and are unable to |
+ | obtain it through the world-wide-web, please send a note to |
+ | [email protected] so we can mail you a copy immediately. |
+ +----------------------------------------------------------------------+
+ | Authors: Saki Takamachi <[email protected]> |
+ +----------------------------------------------------------------------+
+*/
+
+
+#ifndef _BCMATH_SIMD_H_
+#define _BCMATH_SIMD_H_
+
+#ifdef __SSE2__
+# include <emmintrin.h>
+ typedef __m128i bc_simd_128_t;
+# define HAVE_BC_SIMD_128
+# define bc_simd_set_8x16(x) _mm_set1_epi8(x)
+# define bc_simd_load_8x16(ptr) _mm_loadu_si128((const __m128i *) (ptr))
+# define bc_simd_xor_8x16(a, b) _mm_xor_si128(a, b)
+# define bc_simd_store_8x16(ptr, val) _mm_storeu_si128((__m128i *) (ptr), val)
+# define bc_simd_add_8x16(a, b) _mm_add_epi8(a, b)
+# define bc_simd_cmpeq_8x16(a, b) _mm_cmpeq_epi8(a, b)
+# define bc_simd_cmplt_8x16(a, b) _mm_cmplt_epi8(a, b)
+# define bc_simd_movemask_8x16(a) _mm_movemask_epi8(a)
+
+#elif defined(__aarch64__) || defined(_M_ARM64)
+# include <arm_neon.h>
+ typedef int8x16_t bc_simd_128_t;
+# define HAVE_BC_SIMD_128
+# define bc_simd_set_8x16(x) vdupq_n_s8(x)
+# define bc_simd_load_8x16(ptr) vld1q_s8((const int8_t *) (ptr))
+# define bc_simd_xor_8x16(a, b) veorq_s8(a, b)
+# define bc_simd_store_8x16(ptr, val) vst1q_s8((int8_t *) (ptr), val)
+# define bc_simd_add_8x16(a, b) vaddq_s8(a, b)
+# define bc_simd_cmpeq_8x16(a, b) (vreinterpretq_s8_u8(vceqq_s8(a, b)))
+# define bc_simd_cmplt_8x16(a, b) (vreinterpretq_s8_u8(vcltq_s8(a, b)))
+ static inline int bc_simd_movemask_8x16(int8x16_t vec)
+ {
+ /**
+ * based on code from
+ * https://community.arm.com/arm-community-blogs/b/servers-and-cloud-computing-blog/posts/porting-x86-vector-bitmask-optimizations-to-arm-neon
+ */
+ uint16x8_t high_bits = vreinterpretq_u16_u8(vshrq_n_u8(vreinterpretq_u8_s8(vec), 7));
+ uint32x4_t paired16 = vreinterpretq_u32_u16(vsraq_n_u16(high_bits, high_bits, 7));
+ uint64x2_t paired32 = vreinterpretq_u64_u32(vsraq_n_u32(paired16, paired16, 14));
+ uint8x16_t paired64 = vreinterpretq_u8_u64(vsraq_n_u64(paired32, paired32, 28));
+ return vgetq_lane_u8(paired64, 0) | ((int) vgetq_lane_u8(paired64, 8) << 8);
+ }
+#endif
+
+#endif
diff --git a/ext/bcmath/libbcmath/src/str2num.c b/ext/bcmath/libbcmath/src/str2num.c
index bd9a44a240503..945de0cf60003 100644
--- a/ext/bcmath/libbcmath/src/str2num.c
+++ b/ext/bcmath/libbcmath/src/str2num.c
@@ -32,30 +32,28 @@
#include "bcmath.h"
#include "convert.h"
#include "private.h"
+#include "simd.h"
#include <stdbool.h>
#include <stddef.h>
-#ifdef __SSE2__
-# include <emmintrin.h>
-#endif
/* Convert strings to bc numbers. Base 10 only.*/
-static const char *bc_count_digits(const char *str, const char *end)
+static inline const char *bc_count_digits(const char *str, const char *end)
{
/* Process in bulk */
-#ifdef __SSE2__
- const __m128i offset = _mm_set1_epi8((signed char) (SCHAR_MIN - '0'));
+#ifdef HAVE_BC_SIMD_128
+ const bc_simd_128_t offset = bc_simd_set_8x16((signed char) (SCHAR_MIN - '0'));
/* we use the less than comparator, so add 1 */
- const __m128i threshold = _mm_set1_epi8(SCHAR_MIN + ('9' + 1 - '0'));
+ const bc_simd_128_t threshold = bc_simd_set_8x16(SCHAR_MIN + ('9' + 1 - '0'));
- while (str + sizeof(__m128i) <= end) {
- __m128i bytes = _mm_loadu_si128((const __m128i *) str);
+ while (str + sizeof(bc_simd_128_t) <= end) {
+ bc_simd_128_t bytes = bc_simd_load_8x16((const bc_simd_128_t *) str);
/* Wrapping-add the offset to the bytes, such that all bytes below '0' are positive and others are negative.
* More specifically, '0' will be -128 and '9' will be -119. */
- bytes = _mm_add_epi8(bytes, offset);
+ bytes = bc_simd_add_8x16(bytes, offset);
/* Now mark all bytes that are <= '9', i.e. <= -119, i.e. < -118, i.e. the threshold. */
- bytes = _mm_cmplt_epi8(bytes, threshold);
+ bytes = bc_simd_cmplt_8x16(bytes, threshold);
- int mask = _mm_movemask_epi8(bytes);
+ int mask = bc_simd_movemask_8x16(bytes);
if (mask != 0xffff) {
/* At least one of the bytes is not within range. Move to the first offending byte. */
#ifdef PHP_HAVE_BUILTIN_CTZL
@@ -65,7 +63,7 @@ static const char *bc_count_digits(const char *str, const char *end)
#endif
}
- str += sizeof(__m128i);
+ str += sizeof(bc_simd_128_t);
}
#endif
@@ -79,19 +77,19 @@ static const char *bc_count_digits(const char *str, const char *end)
static inline const char *bc_skip_zero_reverse(const char *scanner, const char *stop)
{
/* Check in bulk */
-#ifdef __SSE2__
- const __m128i c_zero_repeat = _mm_set1_epi8('0');
- while (scanner - sizeof(__m128i) >= stop) {
- scanner -= sizeof(__m128i);
- __m128i bytes = _mm_loadu_si128((const __m128i *) scanner);
+#ifdef HAVE_BC_SIMD_128
+ const bc_simd_128_t c_zero_repeat = bc_simd_set_8x16('0');
+ while (scanner - sizeof(bc_simd_128_t) >= stop) {
+ scanner -= sizeof(bc_simd_128_t);
+ bc_simd_128_t bytes = bc_simd_load_8x16((const bc_simd_128_t *) scanner);
/* Checks if all numeric strings are equal to '0'. */
- bytes = _mm_cmpeq_epi8(bytes, c_zero_repeat);
+ bytes = bc_simd_cmpeq_8x16(bytes, c_zero_repeat);
- int mask = _mm_movemask_epi8(bytes);
+ int mask = bc_simd_movemask_8x16(bytes);
/* The probability of having 16 trailing 0s in a row is very low, so we use EXPECTED. */
if (EXPECTED(mask != 0xffff)) {
/* Move the pointer back and check each character in loop. */
- scanner += sizeof(__m128i);
+ scanner += sizeof(bc_simd_128_t);
break;
}
}
| diff --git a/ext/bcmath/libbcmath/src/convert.c b/ext/bcmath/libbcmath/src/convert.c
index bf3d9a9a415bf..5438b4c1c44e5 100644
--- a/ext/bcmath/libbcmath/src/convert.c
+++ b/ext/bcmath/libbcmath/src/convert.c
@@ -17,24 +17,22 @@
char *bc_copy_and_toggle_bcd(char *restrict dest, const char *source, const char *source_end)
const size_t bulk_shift = SWAR_REPEAT('0');
- /* SIMD SSE2 bulk shift + copy */
- while (source + sizeof(__m128i) <= source_end) {
- __m128i bytes = _mm_loadu_si128((const __m128i *) source);
- bytes = _mm_xor_si128(bytes, shift_vector);
- _mm_storeu_si128((__m128i *) dest, bytes);
+ /* SIMD SSE2 or NEON bulk shift + copy */
+ while (source + sizeof(bc_simd_128_t) <= source_end) {
+ bc_simd_128_t bytes = bc_simd_load_8x16((const bc_simd_128_t *) source);
+ bc_simd_store_8x16((bc_simd_128_t *) dest, bytes);
- source += sizeof(__m128i);
- dest += sizeof(__m128i);
+ source += sizeof(bc_simd_128_t);
+ dest += sizeof(bc_simd_128_t);
diff --git a/ext/bcmath/libbcmath/src/simd.h b/ext/bcmath/libbcmath/src/simd.h
new file mode 100644
index 0000000000000..af38f8349618c
--- /dev/null
+++ b/ext/bcmath/libbcmath/src/simd.h
@@ -0,0 +1,59 @@
+/*
+ | Copyright (c) The PHP Group |
+ | This source file is subject to version 3.01 of the PHP license, |
+ | that is bundled with this package in the file LICENSE, and is |
+ | available through the world-wide-web at the following url: |
+ | https://www.php.net/license/3_01.txt |
+ | If you did not receive a copy of the PHP license and are unable to |
+ | obtain it through the world-wide-web, please send a note to |
+ | [email protected] so we can mail you a copy immediately. |
+ | Authors: Saki Takamachi <[email protected]> |
+*/
+#ifndef _BCMATH_SIMD_H_
+#define _BCMATH_SIMD_H_
+# include <emmintrin.h>
+# define bc_simd_set_8x16(x) _mm_set1_epi8(x)
+# define bc_simd_load_8x16(ptr) _mm_loadu_si128((const __m128i *) (ptr))
+# define bc_simd_xor_8x16(a, b) _mm_xor_si128(a, b)
+# define bc_simd_store_8x16(ptr, val) _mm_storeu_si128((__m128i *) (ptr), val)
+# define bc_simd_add_8x16(a, b) _mm_add_epi8(a, b)
+# define bc_simd_cmpeq_8x16(a, b) _mm_cmpeq_epi8(a, b)
+# define bc_simd_movemask_8x16(a) _mm_movemask_epi8(a)
+#elif defined(__aarch64__) || defined(_M_ARM64)
+# include <arm_neon.h>
+ typedef int8x16_t bc_simd_128_t;
+# define bc_simd_set_8x16(x) vdupq_n_s8(x)
+# define bc_simd_load_8x16(ptr) vld1q_s8((const int8_t *) (ptr))
+# define bc_simd_xor_8x16(a, b) veorq_s8(a, b)
+# define bc_simd_store_8x16(ptr, val) vst1q_s8((int8_t *) (ptr), val)
+# define bc_simd_cmpeq_8x16(a, b) (vreinterpretq_s8_u8(vceqq_s8(a, b)))
+# define bc_simd_cmplt_8x16(a, b) (vreinterpretq_s8_u8(vcltq_s8(a, b)))
+ static inline int bc_simd_movemask_8x16(int8x16_t vec)
+ {
+ /**
+ * based on code from
+ */
+ uint16x8_t high_bits = vreinterpretq_u16_u8(vshrq_n_u8(vreinterpretq_u8_s8(vec), 7));
+ uint32x4_t paired16 = vreinterpretq_u32_u16(vsraq_n_u16(high_bits, high_bits, 7));
+ uint64x2_t paired32 = vreinterpretq_u64_u32(vsraq_n_u32(paired16, paired16, 14));
+ uint8x16_t paired64 = vreinterpretq_u8_u64(vsraq_n_u64(paired32, paired32, 28));
+ return vgetq_lane_u8(paired64, 0) | ((int) vgetq_lane_u8(paired64, 8) << 8);
diff --git a/ext/bcmath/libbcmath/src/str2num.c b/ext/bcmath/libbcmath/src/str2num.c
index bd9a44a240503..945de0cf60003 100644
--- a/ext/bcmath/libbcmath/src/str2num.c
+++ b/ext/bcmath/libbcmath/src/str2num.c
@@ -32,30 +32,28 @@
#include <stdbool.h>
#include <stddef.h>
/* Convert strings to bc numbers. Base 10 only.*/
-static const char *bc_count_digits(const char *str, const char *end)
+static inline const char *bc_count_digits(const char *str, const char *end)
/* Process in bulk */
- const __m128i offset = _mm_set1_epi8((signed char) (SCHAR_MIN - '0'));
+ const bc_simd_128_t offset = bc_simd_set_8x16((signed char) (SCHAR_MIN - '0'));
/* we use the less than comparator, so add 1 */
- const __m128i threshold = _mm_set1_epi8(SCHAR_MIN + ('9' + 1 - '0'));
+ const bc_simd_128_t threshold = bc_simd_set_8x16(SCHAR_MIN + ('9' + 1 - '0'));
- while (str + sizeof(__m128i) <= end) {
- __m128i bytes = _mm_loadu_si128((const __m128i *) str);
+ while (str + sizeof(bc_simd_128_t) <= end) {
+ bc_simd_128_t bytes = bc_simd_load_8x16((const bc_simd_128_t *) str);
/* Wrapping-add the offset to the bytes, such that all bytes below '0' are positive and others are negative.
* More specifically, '0' will be -128 and '9' will be -119. */
- bytes = _mm_add_epi8(bytes, offset);
+ bytes = bc_simd_add_8x16(bytes, offset);
/* Now mark all bytes that are <= '9', i.e. <= -119, i.e. < -118, i.e. the threshold. */
- bytes = _mm_cmplt_epi8(bytes, threshold);
+ bytes = bc_simd_cmplt_8x16(bytes, threshold);
if (mask != 0xffff) {
/* At least one of the bytes is not within range. Move to the first offending byte. */
#ifdef PHP_HAVE_BUILTIN_CTZL
@@ -65,7 +63,7 @@ static const char *bc_count_digits(const char *str, const char *end)
- str += sizeof(__m128i);
+ str += sizeof(bc_simd_128_t);
@@ -79,19 +77,19 @@ static const char *bc_count_digits(const char *str, const char *end)
static inline const char *bc_skip_zero_reverse(const char *scanner, const char *stop)
/* Check in bulk */
- const __m128i c_zero_repeat = _mm_set1_epi8('0');
- while (scanner - sizeof(__m128i) >= stop) {
- scanner -= sizeof(__m128i);
+ const bc_simd_128_t c_zero_repeat = bc_simd_set_8x16('0');
+ while (scanner - sizeof(bc_simd_128_t) >= stop) {
+ scanner -= sizeof(bc_simd_128_t);
+ bc_simd_128_t bytes = bc_simd_load_8x16((const bc_simd_128_t *) scanner);
/* Checks if all numeric strings are equal to '0'. */
- bytes = _mm_cmpeq_epi8(bytes, c_zero_repeat);
+ bytes = bc_simd_cmpeq_8x16(bytes, c_zero_repeat);
/* The probability of having 16 trailing 0s in a row is very low, so we use EXPECTED. */
if (EXPECTED(mask != 0xffff)) {
/* Move the pointer back and check each character in loop. */
- scanner += sizeof(__m128i);
+ scanner += sizeof(bc_simd_128_t);
break; | [
"-\t__m128i shift_vector = _mm_set1_epi8('0');",
"+\tbc_simd_128_t shift_vector = bc_simd_set_8x16('0');",
"+\t\tbytes = bc_simd_xor_8x16(bytes, shift_vector);",
"+#ifdef __SSE2__",
"+ typedef __m128i bc_simd_128_t;",
"+# define bc_simd_cmplt_8x16(a, b) _mm_cmplt_epi8(a, b)",
"+# define bc_simd_add_8x16(a, b) vaddq_s8(a, b)",
"+ * https://community.arm.com/arm-community-blogs/b/servers-and-cloud-computing-blog/posts/porting-x86-vector-bitmask-optimizations-to-arm-neon",
"+ }",
"-\t\t__m128i bytes = _mm_loadu_si128((const __m128i *) scanner);"
] | [
19,
26,
29,
65,
67,
75,
86,
93,
100,
166
] | {
"additions": 88,
"author": "SakiTakamachi",
"deletions": 33,
"html_url": "https://github.com/php/php-src/pull/18130",
"issue_id": 18130,
"merged_at": "2025-03-25T22:48:03Z",
"omission_probability": 0.1,
"pr_number": 18130,
"repo": "php/php-src",
"title": "ext/bcmath: In the arm processor environment, NEON is used to use SIMD.",
"total_changes": 121
} |
786 | diff --git a/ext/enchant/enchant.c b/ext/enchant/enchant.c
index bcea06a83d7ad..d1d9ee60c440a 100644
--- a/ext/enchant/enchant.c
+++ b/ext/enchant/enchant.c
@@ -113,9 +113,9 @@ enumerate_providers_fn (const char * const name,
array_init(&tmp_array);
- add_assoc_string(&tmp_array, "name", (char *)name);
- add_assoc_string(&tmp_array, "desc", (char *)desc);
- add_assoc_string(&tmp_array, "file", (char *)file);
+ add_assoc_string(&tmp_array, "name", name);
+ add_assoc_string(&tmp_array, "desc", desc);
+ add_assoc_string(&tmp_array, "file", file);
add_next_index_zval(zdesc, &tmp_array);
}
/* }}} */
@@ -129,10 +129,10 @@ describe_dict_fn (const char * const lang,
{
zval *zdesc = (zval *) ud;
array_init(zdesc);
- add_assoc_string(zdesc, "lang", (char *)lang);
- add_assoc_string(zdesc, "name", (char *)name);
- add_assoc_string(zdesc, "desc", (char *)desc);
- add_assoc_string(zdesc, "file", (char *)file);
+ add_assoc_string(zdesc, "lang", lang);
+ add_assoc_string(zdesc, "name", name);
+ add_assoc_string(zdesc, "desc", desc);
+ add_assoc_string(zdesc, "file", file);
}
/* }}} */
@@ -144,10 +144,10 @@ static void php_enchant_list_dicts_fn( const char * const lang_tag,
zval tmp_array;
array_init(&tmp_array);
- add_assoc_string(&tmp_array, "lang_tag", (char *)lang_tag);
- add_assoc_string(&tmp_array, "provider_name", (char *)provider_name);
- add_assoc_string(&tmp_array, "provider_desc", (char *)provider_desc);
- add_assoc_string(&tmp_array, "provider_file", (char *)provider_file);
+ add_assoc_string(&tmp_array, "lang_tag", lang_tag);
+ add_assoc_string(&tmp_array, "provider_name", provider_name);
+ add_assoc_string(&tmp_array, "provider_desc", provider_desc);
+ add_assoc_string(&tmp_array, "provider_file", provider_file);
add_next_index_zval(zdesc, &tmp_array);
}
@@ -318,7 +318,7 @@ PHP_FUNCTION(enchant_broker_get_error)
msg = enchant_broker_get_error(pbroker->pbroker);
if (msg) {
- RETURN_STRING((char *)msg);
+ RETURN_STRING(msg);
}
RETURN_FALSE;
}
@@ -346,12 +346,12 @@ PHP_FUNCTION(enchant_broker_set_dict_path)
switch (dict_type) {
case PHP_ENCHANT_MYSPELL:
- enchant_broker_set_param(pbroker->pbroker, "enchant.myspell.dictionary.path", (const char *)value);
+ enchant_broker_set_param(pbroker->pbroker, "enchant.myspell.dictionary.path", value);
RETURN_TRUE;
break;
case PHP_ENCHANT_ISPELL:
- enchant_broker_set_param(pbroker->pbroker, "enchant.ispell.dictionary.path", (const char *)value);
+ enchant_broker_set_param(pbroker->pbroker, "enchant.ispell.dictionary.path", value);
RETURN_TRUE;
break;
@@ -440,7 +440,7 @@ PHP_FUNCTION(enchant_broker_request_dict)
RETURN_THROWS();
}
- pdict = enchant_broker_request_dict(pbroker->pbroker, (const char *)tag);
+ pdict = enchant_broker_request_dict(pbroker->pbroker, tag);
if (pdict) {
pbroker->nb_dict++;
| diff --git a/ext/enchant/enchant.c b/ext/enchant/enchant.c
index bcea06a83d7ad..d1d9ee60c440a 100644
--- a/ext/enchant/enchant.c
+++ b/ext/enchant/enchant.c
@@ -113,9 +113,9 @@ enumerate_providers_fn (const char * const name,
- add_assoc_string(&tmp_array, "name", (char *)name);
- add_assoc_string(&tmp_array, "desc", (char *)desc);
- add_assoc_string(&tmp_array, "file", (char *)file);
+ add_assoc_string(&tmp_array, "name", name);
+ add_assoc_string(&tmp_array, "desc", desc);
+ add_assoc_string(&tmp_array, "file", file);
@@ -129,10 +129,10 @@ describe_dict_fn (const char * const lang,
{
zval *zdesc = (zval *) ud;
array_init(zdesc);
- add_assoc_string(zdesc, "lang", (char *)lang);
- add_assoc_string(zdesc, "name", (char *)name);
- add_assoc_string(zdesc, "desc", (char *)desc);
- add_assoc_string(zdesc, "file", (char *)file);
+ add_assoc_string(zdesc, "lang", lang);
+ add_assoc_string(zdesc, "desc", desc);
+ add_assoc_string(zdesc, "file", file);
@@ -144,10 +144,10 @@ static void php_enchant_list_dicts_fn( const char * const lang_tag,
zval tmp_array;
- add_assoc_string(&tmp_array, "lang_tag", (char *)lang_tag);
- add_assoc_string(&tmp_array, "provider_name", (char *)provider_name);
- add_assoc_string(&tmp_array, "provider_desc", (char *)provider_desc);
- add_assoc_string(&tmp_array, "provider_file", (char *)provider_file);
+ add_assoc_string(&tmp_array, "lang_tag", lang_tag);
+ add_assoc_string(&tmp_array, "provider_name", provider_name);
+ add_assoc_string(&tmp_array, "provider_desc", provider_desc);
+ add_assoc_string(&tmp_array, "provider_file", provider_file);
@@ -318,7 +318,7 @@ PHP_FUNCTION(enchant_broker_get_error)
msg = enchant_broker_get_error(pbroker->pbroker);
if (msg) {
- RETURN_STRING((char *)msg);
+ RETURN_STRING(msg);
RETURN_FALSE;
@@ -346,12 +346,12 @@ PHP_FUNCTION(enchant_broker_set_dict_path)
switch (dict_type) {
case PHP_ENCHANT_MYSPELL:
+ enchant_broker_set_param(pbroker->pbroker, "enchant.myspell.dictionary.path", value);
case PHP_ENCHANT_ISPELL:
- enchant_broker_set_param(pbroker->pbroker, "enchant.ispell.dictionary.path", (const char *)value);
+ enchant_broker_set_param(pbroker->pbroker, "enchant.ispell.dictionary.path", value);
@@ -440,7 +440,7 @@ PHP_FUNCTION(enchant_broker_request_dict)
RETURN_THROWS();
- pdict = enchant_broker_request_dict(pbroker->pbroker, (const char *)tag);
+ pdict = enchant_broker_request_dict(pbroker->pbroker, tag);
if (pdict) {
pbroker->nb_dict++; | [
"+\tadd_assoc_string(zdesc, \"name\", name);",
"-\t\t\tenchant_broker_set_param(pbroker->pbroker, \"enchant.myspell.dictionary.path\", (const char *)value);"
] | [
26,
60
] | {
"additions": 15,
"author": "Girgias",
"deletions": 15,
"html_url": "https://github.com/php/php-src/pull/18141",
"issue_id": 18141,
"merged_at": "2025-03-25T06:59:57Z",
"omission_probability": 0.1,
"pr_number": 18141,
"repo": "php/php-src",
"title": "ext/enchant: Remove useless char* casts",
"total_changes": 30
} |
787 | diff --git a/ext/bz2/tests/004.phpt b/ext/bz2/tests/004.phpt
index e644bfa6ce962..240cef37a17a2 100644
--- a/ext/bz2/tests/004.phpt
+++ b/ext/bz2/tests/004.phpt
@@ -112,8 +112,8 @@ array(2) {
}
string(10) "DATA_ERROR"
int(-4)
-bzread(): supplied resource is not a valid stream resource
-bzerror(): supplied resource is not a valid stream resource
-bzerrstr(): supplied resource is not a valid stream resource
-bzerrno(): supplied resource is not a valid stream resource
+bzread(): Argument #1 ($bz) must be an open stream resource
+bzerror(): Argument #1 ($bz) must be an open stream resource
+bzerrstr(): Argument #1 ($bz) must be an open stream resource
+bzerrno(): Argument #1 ($bz) must be an open stream resource
Done
diff --git a/ext/sockets/tests/socket_export_stream-4-win.phpt b/ext/sockets/tests/socket_export_stream-4-win.phpt
index 9eb2b901e1c65..57c7e7a9aeed2 100644
--- a/ext/sockets/tests/socket_export_stream-4-win.phpt
+++ b/ext/sockets/tests/socket_export_stream-4-win.phpt
@@ -92,7 +92,7 @@ stream_set_blocking 1
close stream
-stream_set_blocking TypeError: stream_set_blocking(): supplied resource is not a valid stream resource
+stream_set_blocking TypeError: stream_set_blocking(): Argument #1 ($stream) must be an open stream resource
socket_set_block
Warning: socket_set_block(): unable to set blocking mode [%d]: An operation was attempted on something that is not a socket in %s on line %d
@@ -103,7 +103,7 @@ Warning: socket_get_option(): Unable to retrieve socket option [%d]: An operatio
close socket
-stream_set_blocking TypeError: stream_set_blocking(): supplied resource is not a valid stream resource
+stream_set_blocking TypeError: stream_set_blocking(): Argument #1 ($stream) must be an open stream resource
socket_set_block Error: socket_set_block(): Argument #1 ($socket) has already been closed
diff --git a/ext/sockets/tests/socket_export_stream-4.phpt b/ext/sockets/tests/socket_export_stream-4.phpt
index b8b6c954099c7..512a62379e98c 100644
--- a/ext/sockets/tests/socket_export_stream-4.phpt
+++ b/ext/sockets/tests/socket_export_stream-4.phpt
@@ -94,7 +94,7 @@ stream_set_blocking 1
close stream
-stream_set_blocking TypeError: stream_set_blocking(): supplied resource is not a valid stream resource
+stream_set_blocking TypeError: stream_set_blocking(): Argument #1 ($stream) must be an open stream resource
socket_set_block
Warning: socket_set_block(): unable to set blocking mode [%d]: %s in %s on line %d
@@ -105,7 +105,7 @@ Warning: socket_get_option(): Unable to retrieve socket option [%d]: %s in %s on
close socket
-stream_set_blocking TypeError: stream_set_blocking(): supplied resource is not a valid stream resource
+stream_set_blocking TypeError: stream_set_blocking(): Argument #1 ($stream) must be an open stream resource
socket_set_block Error: socket_set_block(): Argument #1 ($socket) has already been closed
diff --git a/ext/sockets/tests/socket_import_stream-4-win.phpt b/ext/sockets/tests/socket_import_stream-4-win.phpt
index a005347069ed3..ab09f43d92075 100644
--- a/ext/sockets/tests/socket_import_stream-4-win.phpt
+++ b/ext/sockets/tests/socket_import_stream-4-win.phpt
@@ -87,7 +87,7 @@ stream_set_blocking 1
close stream
-stream_set_blocking TypeError: stream_set_blocking(): supplied resource is not a valid stream resource
+stream_set_blocking TypeError: stream_set_blocking(): Argument #1 ($stream) must be an open stream resource
socket_set_block
Warning: socket_set_block(): unable to set blocking mode [10038]: %s in %ssocket_import_stream-4-win.php on line %d
@@ -98,7 +98,7 @@ Warning: socket_get_option(): Unable to retrieve socket option [10038]: %s in %s
close socket
-stream_set_blocking TypeError: stream_set_blocking(): supplied resource is not a valid stream resource
+stream_set_blocking TypeError: stream_set_blocking(): Argument #1 ($stream) must be an open stream resource
socket_set_block Error: socket_set_block(): Argument #1 ($socket) has already been closed
diff --git a/ext/sockets/tests/socket_import_stream-4.phpt b/ext/sockets/tests/socket_import_stream-4.phpt
index c898d614bcff5..25e425961f613 100644
--- a/ext/sockets/tests/socket_import_stream-4.phpt
+++ b/ext/sockets/tests/socket_import_stream-4.phpt
@@ -89,7 +89,7 @@ stream_set_blocking 1
close stream
-stream_set_blocking TypeError: stream_set_blocking(): supplied resource is not a valid stream resource
+stream_set_blocking TypeError: stream_set_blocking(): Argument #1 ($stream) must be an open stream resource
socket_set_block
Warning: socket_set_block(): unable to set blocking mode [%d]: %s in %s on line %d
@@ -100,7 +100,7 @@ Warning: socket_get_option(): Unable to retrieve socket option [%d]: %s in %s on
close socket
-stream_set_blocking TypeError: stream_set_blocking(): supplied resource is not a valid stream resource
+stream_set_blocking TypeError: stream_set_blocking(): Argument #1 ($stream) must be an open stream resource
socket_set_block Error: socket_set_block(): Argument #1 ($socket) has already been closed
diff --git a/ext/spl/tests/bug81691.phpt b/ext/spl/tests/bug81691.phpt
index 597e37a9c8218..5ae5dd6b08fda 100644
--- a/ext/spl/tests/bug81691.phpt
+++ b/ext/spl/tests/bug81691.phpt
@@ -10,6 +10,6 @@ var_dump($obj->fgets());
?>
--EXPECTF--
-Warning: fclose(): %d is not a valid stream resource in %s on line %d
+Warning: fclose(): cannot close the provided stream, as it must not be manually closed in %s on line %d
string(6) "<?php
"
diff --git a/ext/standard/file.c b/ext/standard/file.c
index 908aee85a2e74..4e136bedf5fab 100644
--- a/ext/standard/file.c
+++ b/ext/standard/file.c
@@ -757,7 +757,7 @@ PHPAPI PHP_FUNCTION(fclose)
ZEND_PARSE_PARAMETERS_END();
if ((stream->flags & PHP_STREAM_FLAG_NO_FCLOSE) != 0) {
- php_error_docref(NULL, E_WARNING, ZEND_LONG_FMT " is not a valid stream resource", stream->res->handle);
+ php_error_docref(NULL, E_WARNING, "cannot close the provided stream, as it must not be manually closed");
RETURN_FALSE;
}
diff --git a/ext/standard/tests/file/007_basic.phpt b/ext/standard/tests/file/007_basic.phpt
index 37047ec32b28b..6a0c918ea39c8 100644
--- a/ext/standard/tests/file/007_basic.phpt
+++ b/ext/standard/tests/file/007_basic.phpt
@@ -102,8 +102,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'wb' --
resource(%d) of type (stream)
@@ -111,8 +111,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'wt' --
resource(%d) of type (stream)
@@ -120,8 +120,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'w+' --
resource(%d) of type (stream)
@@ -129,8 +129,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'w+b' --
resource(%d) of type (stream)
@@ -138,8 +138,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'w+t' --
resource(%d) of type (stream)
@@ -147,8 +147,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'r' --
resource(%d) of type (stream)
@@ -156,8 +156,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'rb' --
resource(%d) of type (stream)
@@ -165,8 +165,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'rt' --
resource(%d) of type (stream)
@@ -174,8 +174,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'r+' --
resource(%d) of type (stream)
@@ -183,8 +183,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'r+b' --
resource(%d) of type (stream)
@@ -192,8 +192,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'r+t' --
resource(%d) of type (stream)
@@ -201,8 +201,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'a' --
resource(%d) of type (stream)
@@ -210,8 +210,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'ab' --
resource(%d) of type (stream)
@@ -219,8 +219,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'at' --
resource(%d) of type (stream)
@@ -228,8 +228,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'a+' --
resource(%d) of type (stream)
@@ -237,8 +237,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'a+t' --
resource(%d) of type (stream)
@@ -246,8 +246,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'a+b' --
resource(%d) of type (stream)
@@ -255,8 +255,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
-- Iteration with mode 'x' --
resource(%d) of type (stream)
@@ -264,8 +264,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
resource(%d) of type (Unknown)
-- Iteration with mode 'xb' --
@@ -274,8 +274,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
resource(%d) of type (Unknown)
-- Iteration with mode 'xt' --
@@ -284,8 +284,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
resource(%d) of type (Unknown)
-- Iteration with mode 'x+' --
@@ -294,8 +294,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
resource(%d) of type (Unknown)
-- Iteration with mode 'x+b' --
@@ -304,8 +304,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
resource(%d) of type (Unknown)
-- Iteration with mode 'x+t' --
@@ -314,8 +314,8 @@ int(0)
bool(false)
bool(true)
resource(%d) of type (Unknown)
-ftell(): supplied resource is not a valid stream resource
-feof(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
resource(%d) of type (Unknown)
*** Done ***
diff --git a/ext/standard/tests/file/fclose_variation1.phpt b/ext/standard/tests/file/fclose_variation1.phpt
index 5f6c25860d64f..56a6d4bd4c1c4 100644
--- a/ext/standard/tests/file/fclose_variation1.phpt
+++ b/ext/standard/tests/file/fclose_variation1.phpt
@@ -15,6 +15,6 @@ try {
echo "\nDone.\n";
?>
--EXPECT--
-fread(): supplied resource is not a valid stream resource
+fread(): Argument #1 ($stream) must be an open stream resource
Done.
diff --git a/ext/standard/tests/file/feof_basic.phpt b/ext/standard/tests/file/feof_basic.phpt
index a263bf1fbe6c4..943af213e39a2 100644
--- a/ext/standard/tests/file/feof_basic.phpt
+++ b/ext/standard/tests/file/feof_basic.phpt
@@ -94,5 +94,5 @@ bool(false)
*** testing feof after a seek passed the end ***
bool(false)
*** closing file, testing eof ***
-feof(): supplied resource is not a valid stream resource
+feof(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/file/fgetc_variation2.phpt b/ext/standard/tests/file/fgetc_variation2.phpt
index 42558998337ed..89161d0881902 100644
--- a/ext/standard/tests/file/fgetc_variation2.phpt
+++ b/ext/standard/tests/file/fgetc_variation2.phpt
@@ -30,5 +30,5 @@ echo "Done";
--EXPECT--
*** Testing fgetc() : usage variations ***
-- Testing fgetc() with closed handle --
-fgetc(): supplied resource is not a valid stream resource
+fgetc(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/file/fgets_variation2.phpt b/ext/standard/tests/file/fgets_variation2.phpt
index 28cba347d5ff7..5d262cde295b4 100644
--- a/ext/standard/tests/file/fgets_variation2.phpt
+++ b/ext/standard/tests/file/fgets_variation2.phpt
@@ -35,6 +35,6 @@ echo "Done";
--EXPECT--
*** Testing fgets() : usage variations ***
-- Testing fgets() with closed handle --
-fgets(): supplied resource is not a valid stream resource
-fgets(): supplied resource is not a valid stream resource
+fgets(): Argument #1 ($stream) must be an open stream resource
+fgets(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/file/flock.phpt b/ext/standard/tests/file/flock.phpt
index 346029c7cab27..a3c1804584023 100644
--- a/ext/standard/tests/file/flock.phpt
+++ b/ext/standard/tests/file/flock.phpt
@@ -46,7 +46,7 @@ $file = __DIR__."/flock.dat";
unlink($file);
?>
--EXPECT--
-flock(): supplied resource is not a valid stream resource
+flock(): Argument #1 ($stream) must be an open stream resource
bool(true)
bool(true)
bool(true)
diff --git a/ext/standard/tests/file/flock_error.phpt b/ext/standard/tests/file/flock_error.phpt
index 753aaa6fb34e8..2ca20c3436ab6 100644
--- a/ext/standard/tests/file/flock_error.phpt
+++ b/ext/standard/tests/file/flock_error.phpt
@@ -70,4 +70,4 @@ flock(): Argument #2 ($operation) must be of type int, string given
flock(): Argument #2 ($operation) must be of type int, string given
--- Iteration 7 ---
flock(): Argument #2 ($operation) must be of type int, string given
-flock(): supplied resource is not a valid stream resource
+flock(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/file/fseek_ftell_rewind_error1.phpt b/ext/standard/tests/file/fseek_ftell_rewind_error1.phpt
index d576403644546..c38f7905399be 100644
--- a/ext/standard/tests/file/fseek_ftell_rewind_error1.phpt
+++ b/ext/standard/tests/file/fseek_ftell_rewind_error1.phpt
@@ -20,5 +20,5 @@ echo "Done\n";
--EXPECT--
*** Testing fseek() : error conditions ***
-- Testing fseek() with closed/unset file handle --
-fseek(): supplied resource is not a valid stream resource
+fseek(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/file/fseek_ftell_rewind_error2.phpt b/ext/standard/tests/file/fseek_ftell_rewind_error2.phpt
index 5a947f66587fe..58c3b5330d874 100644
--- a/ext/standard/tests/file/fseek_ftell_rewind_error2.phpt
+++ b/ext/standard/tests/file/fseek_ftell_rewind_error2.phpt
@@ -20,5 +20,5 @@ echo "Done\n";
--EXPECT--
*** Testing ftell() : error conditions ***
-- Testing ftell with closed/unset file handle --
-ftell(): supplied resource is not a valid stream resource
+ftell(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/file/fseek_ftell_rewind_error3.phpt b/ext/standard/tests/file/fseek_ftell_rewind_error3.phpt
index f4212ec71b427..ad50244edb3e4 100644
--- a/ext/standard/tests/file/fseek_ftell_rewind_error3.phpt
+++ b/ext/standard/tests/file/fseek_ftell_rewind_error3.phpt
@@ -20,5 +20,5 @@ echo "Done\n";
--EXPECT--
*** Testing rewind() : error conditions ***
-- Testing rewind() with closed/unset file handle --
-rewind(): supplied resource is not a valid stream resource
+rewind(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/file/fstat.phpt b/ext/standard/tests/file/fstat.phpt
index b48b06cfe50b9..86d1453f1b728 100644
--- a/ext/standard/tests/file/fstat.phpt
+++ b/ext/standard/tests/file/fstat.phpt
@@ -72,5 +72,5 @@ array(26) {
["blocks"]=>
int(%i)
}
-fstat(): supplied resource is not a valid stream resource
+fstat(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/file/ftruncate_error.phpt b/ext/standard/tests/file/ftruncate_error.phpt
index 752397a461d6f..3397fc25f44ad 100644
--- a/ext/standard/tests/file/ftruncate_error.phpt
+++ b/ext/standard/tests/file/ftruncate_error.phpt
@@ -35,6 +35,6 @@ unlink( $filename );
Initial file size = 36
-- Testing ftruncate() with closed/unset file handle --
-ftruncate(): supplied resource is not a valid stream resource
+ftruncate(): Argument #1 ($stream) must be an open stream resource
int(36)
Done
diff --git a/ext/standard/tests/file/fwrite.phpt b/ext/standard/tests/file/fwrite.phpt
index 1494ea7a0f5e8..12bfb6727ec31 100644
--- a/ext/standard/tests/file/fwrite.phpt
+++ b/ext/standard/tests/file/fwrite.phpt
@@ -17,12 +17,6 @@ var_dump(fwrite($fp, "data", -1));
var_dump(fwrite($fp, "data", 100000));
fclose($fp);
-try {
- var_dump(fwrite($fp, "data", -1));
-} catch (Throwable $e) {
- echo $e::class, ': ', $e->getMessage(), PHP_EOL;
-}
-
var_dump(file_get_contents($filename));
echo "Done\n";
@@ -39,6 +33,5 @@ Notice: fwrite(): Write of 4 bytes failed with errno=9 Bad file descriptor in %s
bool(false)
int(0)
int(4)
-TypeError: fwrite(): supplied resource is not a valid stream resource
string(4) "data"
Done
diff --git a/ext/standard/tests/file/fwrite_error.phpt b/ext/standard/tests/file/fwrite_error.phpt
index d24f7b8084cf0..62ec928a29dfc 100644
--- a/ext/standard/tests/file/fwrite_error.phpt
+++ b/ext/standard/tests/file/fwrite_error.phpt
@@ -40,5 +40,5 @@ unlink( $filename );
int(0)
int(0)
-- Testing fwrite() with closed/unset file handle --
-fwrite(): supplied resource is not a valid stream resource
+fwrite(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/file/stream_supports_lock.phpt b/ext/standard/tests/file/stream_supports_lock.phpt
index 0d2f04b72d9aa..76249e9106ee4 100644
--- a/ext/standard/tests/file/stream_supports_lock.phpt
+++ b/ext/standard/tests/file/stream_supports_lock.phpt
@@ -44,5 +44,5 @@ bool(false)
resource(%d) of type (stream)
bool(false)
resource(%d) of type (stream-context)
-stream_supports_lock(): supplied resource is not a valid stream resource
+stream_supports_lock(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/filters/bug54350.phpt b/ext/standard/tests/filters/bug54350.phpt
index ae00762890857..046db0483a9ae 100644
--- a/ext/standard/tests/filters/bug54350.phpt
+++ b/ext/standard/tests/filters/bug54350.phpt
@@ -22,5 +22,5 @@ fwrite($fd, "foo");
?>
--EXPECTF--
-Warning: fclose(): %d is not a valid stream resource in %s on line %d
-fclose(): supplied resource is not a valid stream resource
+Warning: fclose(): cannot close the provided stream, as it must not be manually closed in %s on line %d
+fclose(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/streams/bug54623.phpt b/ext/standard/tests/streams/bug54623.phpt
index 29d4cbcbeb6c8..d7383fcc8f7ec 100644
--- a/ext/standard/tests/streams/bug54623.phpt
+++ b/ext/standard/tests/streams/bug54623.phpt
@@ -18,4 +18,4 @@ try {
--EXPECTF--
int(%d)
int(%d)
-fwrite(): supplied resource is not a valid stream resource
+fwrite(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/streams/stream_get_meta_data_file_error.phpt b/ext/standard/tests/streams/stream_get_meta_data_file_error.phpt
index 61b6182e70a2c..55bdd1860a479 100644
--- a/ext/standard/tests/streams/stream_get_meta_data_file_error.phpt
+++ b/ext/standard/tests/streams/stream_get_meta_data_file_error.phpt
@@ -19,5 +19,5 @@ echo "Done";
*** Testing stream_get_meta_data() : error conditions ***
-- Testing stream_get_meta_data() function with closed stream resource --
-stream_get_meta_data(): supplied resource is not a valid stream resource
+stream_get_meta_data(): Argument #1 ($stream) must be an open stream resource
Done
diff --git a/ext/standard/tests/streams/stream_set_timeout_error.phpt b/ext/standard/tests/streams/stream_set_timeout_error.phpt
index 58894b7d8c23c..5567cb159914b 100644
--- a/ext/standard/tests/streams/stream_set_timeout_error.phpt
+++ b/ext/standard/tests/streams/stream_set_timeout_error.phpt
@@ -39,7 +39,7 @@ echo "Done";
*** Testing stream_set_timeout() : error conditions ***
-- Testing stream_set_timeout() function with a closed socket --
-stream_set_timeout(): supplied resource is not a valid stream resource
+stream_set_timeout(): Argument #1 ($stream) must be an open stream resource
-- Testing stream_set_timeout() function with a stream that does not support timeouts --
bool(false)
diff --git a/ext/xmlwriter/tests/bug79029.phpt b/ext/xmlwriter/tests/bug79029.phpt
index 7b091e80e84e9..22feb4599e7af 100644
--- a/ext/xmlwriter/tests/bug79029.phpt
+++ b/ext/xmlwriter/tests/bug79029.phpt
@@ -26,7 +26,7 @@ okey
@unlink("bug79029_3.txt");
?>
--EXPECTF--
-Warning: fclose(): %d is not a valid stream resource in %sbug79029.php on line %d
+Warning: fclose(): cannot close the provided stream, as it must not be manually closed in %sbug79029.php on line %d
-Warning: fclose(): %d is not a valid stream resource in %sbug79029.php on line %d
+Warning: fclose(): cannot close the provided stream, as it must not be manually closed in %sbug79029.php on line %d
okey
diff --git a/ext/zlib/tests/gzclose_basic.phpt b/ext/zlib/tests/gzclose_basic.phpt
index 69dc7cfd3a606..c1d6edf4d95e1 100644
--- a/ext/zlib/tests/gzclose_basic.phpt
+++ b/ext/zlib/tests/gzclose_basic.phpt
@@ -34,6 +34,6 @@ try {
?>
--EXPECT--
bool(true)
-gzread(): supplied resource is not a valid stream resource
+gzread(): Argument #1 ($stream) must be an open stream resource
bool(true)
-gzread(): supplied resource is not a valid stream resource
+gzread(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/zlib/tests/gzeof_variation1.phpt b/ext/zlib/tests/gzeof_variation1.phpt
index 40e6899d6e583..fb4191fa7940a 100644
--- a/ext/zlib/tests/gzeof_variation1.phpt
+++ b/ext/zlib/tests/gzeof_variation1.phpt
@@ -24,4 +24,4 @@ unlink($filename);
--EXPECT--
bool(false)
bool(false)
-gzeof(): supplied resource is not a valid stream resource
+gzeof(): Argument #1 ($stream) must be an open stream resource
diff --git a/main/php_streams.h b/main/php_streams.h
index 80cb96951ee14..f534bc27285f1 100644
--- a/main/php_streams.h
+++ b/main/php_streams.h
@@ -287,11 +287,21 @@ END_EXTERN_C()
BEGIN_EXTERN_C()
-static zend_always_inline bool php_stream_zend_parse_arg_into_stream(zval *arg, php_stream **destination_stream_ptr, bool check_null)
-{
+static zend_always_inline bool php_stream_zend_parse_arg_into_stream(
+ zval *arg,
+ php_stream **destination_stream_ptr,
+ bool check_null,
+ uint32_t arg_num
+) {
if (EXPECTED(Z_TYPE_P(arg) == IS_RESOURCE)) {
- *destination_stream_ptr = (php_stream*)zend_fetch_resource2(Z_RES_P(arg), "stream", php_file_le_stream(), php_file_le_pstream());
- if (UNEXPECTED(*destination_stream_ptr == NULL)) {
+ zend_resource *res = Z_RES_P(arg);
+ /* We do not use zend_fetch_resource2() API,
+ * as we want to be able to specify the argument number in the type error */
+ if (EXPECTED(res->type == php_file_le_stream() || res->type == php_file_le_pstream())) {
+ *destination_stream_ptr = (php_stream*)res->ptr;
+ return true;
+ } else {
+ zend_argument_type_error(arg_num, "must be an open stream resource");
return false;
}
} else if (check_null && EXPECTED(Z_TYPE_P(arg) == IS_NULL)) {
@@ -304,7 +314,7 @@ static zend_always_inline bool php_stream_zend_parse_arg_into_stream(zval *arg,
#define PHP_Z_PARAM_STREAM_EX(destination_stream_ptr, check_null) \
Z_PARAM_PROLOGUE(0, 0); \
- if (UNEXPECTED(!php_stream_zend_parse_arg_into_stream(_arg, &destination_stream_ptr, check_null))) { \
+ if (UNEXPECTED(!php_stream_zend_parse_arg_into_stream(_arg, &destination_stream_ptr, check_null, _i))) { \
_error_code = ZPP_ERROR_FAILURE; \
if (!EG(exception)) { \
_expected_type = check_null ? Z_EXPECTED_RESOURCE_OR_NULL : Z_EXPECTED_RESOURCE; \
| diff --git a/ext/bz2/tests/004.phpt b/ext/bz2/tests/004.phpt
index e644bfa6ce962..240cef37a17a2 100644
--- a/ext/bz2/tests/004.phpt
+++ b/ext/bz2/tests/004.phpt
@@ -112,8 +112,8 @@ array(2) {
string(10) "DATA_ERROR"
int(-4)
-bzerror(): supplied resource is not a valid stream resource
-bzerrstr(): supplied resource is not a valid stream resource
-bzerrno(): supplied resource is not a valid stream resource
+bzread(): Argument #1 ($bz) must be an open stream resource
+bzerror(): Argument #1 ($bz) must be an open stream resource
+bzerrno(): Argument #1 ($bz) must be an open stream resource
diff --git a/ext/sockets/tests/socket_export_stream-4-win.phpt b/ext/sockets/tests/socket_export_stream-4-win.phpt
index 9eb2b901e1c65..57c7e7a9aeed2 100644
--- a/ext/sockets/tests/socket_export_stream-4-win.phpt
+++ b/ext/sockets/tests/socket_export_stream-4-win.phpt
@@ -92,7 +92,7 @@ stream_set_blocking 1
Warning: socket_set_block(): unable to set blocking mode [%d]: An operation was attempted on something that is not a socket in %s on line %d
@@ -103,7 +103,7 @@ Warning: socket_get_option(): Unable to retrieve socket option [%d]: An operatio
diff --git a/ext/sockets/tests/socket_export_stream-4.phpt b/ext/sockets/tests/socket_export_stream-4.phpt
index b8b6c954099c7..512a62379e98c 100644
--- a/ext/sockets/tests/socket_export_stream-4.phpt
+++ b/ext/sockets/tests/socket_export_stream-4.phpt
@@ -94,7 +94,7 @@ stream_set_blocking 1
@@ -105,7 +105,7 @@ Warning: socket_get_option(): Unable to retrieve socket option [%d]: %s in %s on
diff --git a/ext/sockets/tests/socket_import_stream-4-win.phpt b/ext/sockets/tests/socket_import_stream-4-win.phpt
index a005347069ed3..ab09f43d92075 100644
--- a/ext/sockets/tests/socket_import_stream-4-win.phpt
+++ b/ext/sockets/tests/socket_import_stream-4-win.phpt
@@ -87,7 +87,7 @@ stream_set_blocking 1
Warning: socket_set_block(): unable to set blocking mode [10038]: %s in %ssocket_import_stream-4-win.php on line %d
@@ -98,7 +98,7 @@ Warning: socket_get_option(): Unable to retrieve socket option [10038]: %s in %s
diff --git a/ext/sockets/tests/socket_import_stream-4.phpt b/ext/sockets/tests/socket_import_stream-4.phpt
index c898d614bcff5..25e425961f613 100644
--- a/ext/sockets/tests/socket_import_stream-4.phpt
+++ b/ext/sockets/tests/socket_import_stream-4.phpt
@@ -89,7 +89,7 @@ stream_set_blocking 1
@@ -100,7 +100,7 @@ Warning: socket_get_option(): Unable to retrieve socket option [%d]: %s in %s on
diff --git a/ext/spl/tests/bug81691.phpt b/ext/spl/tests/bug81691.phpt
index 597e37a9c8218..5ae5dd6b08fda 100644
--- a/ext/spl/tests/bug81691.phpt
+++ b/ext/spl/tests/bug81691.phpt
@@ -10,6 +10,6 @@ var_dump($obj->fgets());
string(6) "<?php
"
diff --git a/ext/standard/file.c b/ext/standard/file.c
index 908aee85a2e74..4e136bedf5fab 100644
--- a/ext/standard/file.c
+++ b/ext/standard/file.c
@@ -757,7 +757,7 @@ PHPAPI PHP_FUNCTION(fclose)
ZEND_PARSE_PARAMETERS_END();
if ((stream->flags & PHP_STREAM_FLAG_NO_FCLOSE) != 0) {
- php_error_docref(NULL, E_WARNING, ZEND_LONG_FMT " is not a valid stream resource", stream->res->handle);
+ php_error_docref(NULL, E_WARNING, "cannot close the provided stream, as it must not be manually closed");
RETURN_FALSE;
}
diff --git a/ext/standard/tests/file/007_basic.phpt b/ext/standard/tests/file/007_basic.phpt
index 37047ec32b28b..6a0c918ea39c8 100644
--- a/ext/standard/tests/file/007_basic.phpt
+++ b/ext/standard/tests/file/007_basic.phpt
@@ -102,8 +102,8 @@ int(0)
-- Iteration with mode 'wb' --
@@ -111,8 +111,8 @@ int(0)
-- Iteration with mode 'wt' --
@@ -120,8 +120,8 @@ int(0)
-- Iteration with mode 'w+' --
@@ -129,8 +129,8 @@ int(0)
-- Iteration with mode 'w+b' --
@@ -138,8 +138,8 @@ int(0)
-- Iteration with mode 'w+t' --
@@ -147,8 +147,8 @@ int(0)
-- Iteration with mode 'r' --
@@ -156,8 +156,8 @@ int(0)
-- Iteration with mode 'rb' --
@@ -165,8 +165,8 @@ int(0)
-- Iteration with mode 'rt' --
@@ -174,8 +174,8 @@ int(0)
-- Iteration with mode 'r+' --
@@ -183,8 +183,8 @@ int(0)
-- Iteration with mode 'r+b' --
@@ -192,8 +192,8 @@ int(0)
-- Iteration with mode 'r+t' --
@@ -201,8 +201,8 @@ int(0)
-- Iteration with mode 'a' --
@@ -210,8 +210,8 @@ int(0)
-- Iteration with mode 'ab' --
@@ -219,8 +219,8 @@ int(0)
-- Iteration with mode 'at' --
@@ -228,8 +228,8 @@ int(0)
-- Iteration with mode 'a+' --
@@ -237,8 +237,8 @@ int(0)
-- Iteration with mode 'a+t' --
@@ -246,8 +246,8 @@ int(0)
-- Iteration with mode 'a+b' --
@@ -255,8 +255,8 @@ int(0)
-- Iteration with mode 'x' --
@@ -264,8 +264,8 @@ int(0)
-- Iteration with mode 'xb' --
@@ -274,8 +274,8 @@ int(0)
-- Iteration with mode 'xt' --
@@ -284,8 +284,8 @@ int(0)
-- Iteration with mode 'x+' --
@@ -294,8 +294,8 @@ int(0)
-- Iteration with mode 'x+b' --
@@ -304,8 +304,8 @@ int(0)
-- Iteration with mode 'x+t' --
@@ -314,8 +314,8 @@ int(0)
*** Done ***
diff --git a/ext/standard/tests/file/fclose_variation1.phpt b/ext/standard/tests/file/fclose_variation1.phpt
index 5f6c25860d64f..56a6d4bd4c1c4 100644
--- a/ext/standard/tests/file/fclose_variation1.phpt
+++ b/ext/standard/tests/file/fclose_variation1.phpt
@@ -15,6 +15,6 @@ try {
echo "\nDone.\n";
-fread(): supplied resource is not a valid stream resource
+fread(): Argument #1 ($stream) must be an open stream resource
Done.
diff --git a/ext/standard/tests/file/feof_basic.phpt b/ext/standard/tests/file/feof_basic.phpt
index a263bf1fbe6c4..943af213e39a2 100644
--- a/ext/standard/tests/file/feof_basic.phpt
+++ b/ext/standard/tests/file/feof_basic.phpt
@@ -94,5 +94,5 @@ bool(false)
*** testing feof after a seek passed the end ***
*** closing file, testing eof ***
diff --git a/ext/standard/tests/file/fgetc_variation2.phpt b/ext/standard/tests/file/fgetc_variation2.phpt
index 42558998337ed..89161d0881902 100644
--- a/ext/standard/tests/file/fgetc_variation2.phpt
+++ b/ext/standard/tests/file/fgetc_variation2.phpt
@@ -30,5 +30,5 @@ echo "Done";
*** Testing fgetc() : usage variations ***
-- Testing fgetc() with closed handle --
+fgetc(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/file/fgets_variation2.phpt b/ext/standard/tests/file/fgets_variation2.phpt
index 28cba347d5ff7..5d262cde295b4 100644
--- a/ext/standard/tests/file/fgets_variation2.phpt
+++ b/ext/standard/tests/file/fgets_variation2.phpt
@@ -35,6 +35,6 @@ echo "Done";
*** Testing fgets() : usage variations ***
-- Testing fgets() with closed handle --
diff --git a/ext/standard/tests/file/flock.phpt b/ext/standard/tests/file/flock.phpt
index 346029c7cab27..a3c1804584023 100644
--- a/ext/standard/tests/file/flock.phpt
+++ b/ext/standard/tests/file/flock.phpt
@@ -46,7 +46,7 @@ $file = __DIR__."/flock.dat";
unlink($file);
diff --git a/ext/standard/tests/file/flock_error.phpt b/ext/standard/tests/file/flock_error.phpt
index 753aaa6fb34e8..2ca20c3436ab6 100644
--- a/ext/standard/tests/file/flock_error.phpt
+++ b/ext/standard/tests/file/flock_error.phpt
@@ -70,4 +70,4 @@ flock(): Argument #2 ($operation) must be of type int, string given
--- Iteration 7 ---
diff --git a/ext/standard/tests/file/fseek_ftell_rewind_error1.phpt b/ext/standard/tests/file/fseek_ftell_rewind_error1.phpt
index d576403644546..c38f7905399be 100644
--- a/ext/standard/tests/file/fseek_ftell_rewind_error1.phpt
+++ b/ext/standard/tests/file/fseek_ftell_rewind_error1.phpt
*** Testing fseek() : error conditions ***
-- Testing fseek() with closed/unset file handle --
-fseek(): supplied resource is not a valid stream resource
+fseek(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/file/fseek_ftell_rewind_error2.phpt b/ext/standard/tests/file/fseek_ftell_rewind_error2.phpt
index 5a947f66587fe..58c3b5330d874 100644
--- a/ext/standard/tests/file/fseek_ftell_rewind_error2.phpt
+++ b/ext/standard/tests/file/fseek_ftell_rewind_error2.phpt
*** Testing ftell() : error conditions ***
-- Testing ftell with closed/unset file handle --
diff --git a/ext/standard/tests/file/fseek_ftell_rewind_error3.phpt b/ext/standard/tests/file/fseek_ftell_rewind_error3.phpt
index f4212ec71b427..ad50244edb3e4 100644
--- a/ext/standard/tests/file/fseek_ftell_rewind_error3.phpt
+++ b/ext/standard/tests/file/fseek_ftell_rewind_error3.phpt
*** Testing rewind() : error conditions ***
-- Testing rewind() with closed/unset file handle --
-rewind(): supplied resource is not a valid stream resource
+rewind(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/file/fstat.phpt b/ext/standard/tests/file/fstat.phpt
index b48b06cfe50b9..86d1453f1b728 100644
--- a/ext/standard/tests/file/fstat.phpt
+++ b/ext/standard/tests/file/fstat.phpt
@@ -72,5 +72,5 @@ array(26) {
["blocks"]=>
int(%i)
-fstat(): supplied resource is not a valid stream resource
+fstat(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/file/ftruncate_error.phpt b/ext/standard/tests/file/ftruncate_error.phpt
index 752397a461d6f..3397fc25f44ad 100644
--- a/ext/standard/tests/file/ftruncate_error.phpt
+++ b/ext/standard/tests/file/ftruncate_error.phpt
@@ -35,6 +35,6 @@ unlink( $filename );
Initial file size = 36
-- Testing ftruncate() with closed/unset file handle --
-ftruncate(): supplied resource is not a valid stream resource
+ftruncate(): Argument #1 ($stream) must be an open stream resource
int(36)
diff --git a/ext/standard/tests/file/fwrite.phpt b/ext/standard/tests/file/fwrite.phpt
index 1494ea7a0f5e8..12bfb6727ec31 100644
--- a/ext/standard/tests/file/fwrite.phpt
+++ b/ext/standard/tests/file/fwrite.phpt
@@ -17,12 +17,6 @@ var_dump(fwrite($fp, "data", -1));
var_dump(fwrite($fp, "data", 100000));
fclose($fp);
-try {
- var_dump(fwrite($fp, "data", -1));
-} catch (Throwable $e) {
- echo $e::class, ': ', $e->getMessage(), PHP_EOL;
-}
-
var_dump(file_get_contents($filename));
echo "Done\n";
@@ -39,6 +33,5 @@ Notice: fwrite(): Write of 4 bytes failed with errno=9 Bad file descriptor in %s
int(4)
-TypeError: fwrite(): supplied resource is not a valid stream resource
string(4) "data"
diff --git a/ext/standard/tests/file/fwrite_error.phpt b/ext/standard/tests/file/fwrite_error.phpt
index d24f7b8084cf0..62ec928a29dfc 100644
--- a/ext/standard/tests/file/fwrite_error.phpt
+++ b/ext/standard/tests/file/fwrite_error.phpt
@@ -40,5 +40,5 @@ unlink( $filename );
-- Testing fwrite() with closed/unset file handle --
diff --git a/ext/standard/tests/file/stream_supports_lock.phpt b/ext/standard/tests/file/stream_supports_lock.phpt
index 0d2f04b72d9aa..76249e9106ee4 100644
--- a/ext/standard/tests/file/stream_supports_lock.phpt
+++ b/ext/standard/tests/file/stream_supports_lock.phpt
@@ -44,5 +44,5 @@ bool(false)
resource(%d) of type (stream-context)
-stream_supports_lock(): supplied resource is not a valid stream resource
+stream_supports_lock(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/filters/bug54350.phpt b/ext/standard/tests/filters/bug54350.phpt
index ae00762890857..046db0483a9ae 100644
--- a/ext/standard/tests/filters/bug54350.phpt
+++ b/ext/standard/tests/filters/bug54350.phpt
@@ -22,5 +22,5 @@ fwrite($fd, "foo");
-fclose(): supplied resource is not a valid stream resource
diff --git a/ext/standard/tests/streams/bug54623.phpt b/ext/standard/tests/streams/bug54623.phpt
index 29d4cbcbeb6c8..d7383fcc8f7ec 100644
--- a/ext/standard/tests/streams/bug54623.phpt
+++ b/ext/standard/tests/streams/bug54623.phpt
@@ -18,4 +18,4 @@ try {
diff --git a/ext/standard/tests/streams/stream_get_meta_data_file_error.phpt b/ext/standard/tests/streams/stream_get_meta_data_file_error.phpt
index 61b6182e70a2c..55bdd1860a479 100644
--- a/ext/standard/tests/streams/stream_get_meta_data_file_error.phpt
+++ b/ext/standard/tests/streams/stream_get_meta_data_file_error.phpt
@@ -19,5 +19,5 @@ echo "Done";
*** Testing stream_get_meta_data() : error conditions ***
-- Testing stream_get_meta_data() function with closed stream resource --
+stream_get_meta_data(): Argument #1 ($stream) must be an open stream resource
diff --git a/ext/standard/tests/streams/stream_set_timeout_error.phpt b/ext/standard/tests/streams/stream_set_timeout_error.phpt
index 58894b7d8c23c..5567cb159914b 100644
--- a/ext/standard/tests/streams/stream_set_timeout_error.phpt
+++ b/ext/standard/tests/streams/stream_set_timeout_error.phpt
@@ -39,7 +39,7 @@ echo "Done";
*** Testing stream_set_timeout() : error conditions ***
-- Testing stream_set_timeout() function with a closed socket --
-stream_set_timeout(): supplied resource is not a valid stream resource
+stream_set_timeout(): Argument #1 ($stream) must be an open stream resource
-- Testing stream_set_timeout() function with a stream that does not support timeouts --
diff --git a/ext/xmlwriter/tests/bug79029.phpt b/ext/xmlwriter/tests/bug79029.phpt
index 7b091e80e84e9..22feb4599e7af 100644
--- a/ext/xmlwriter/tests/bug79029.phpt
+++ b/ext/xmlwriter/tests/bug79029.phpt
@@ -26,7 +26,7 @@ okey
@unlink("bug79029_3.txt");
okey
diff --git a/ext/zlib/tests/gzclose_basic.phpt b/ext/zlib/tests/gzclose_basic.phpt
index 69dc7cfd3a606..c1d6edf4d95e1 100644
--- a/ext/zlib/tests/gzclose_basic.phpt
+++ b/ext/zlib/tests/gzclose_basic.phpt
@@ -34,6 +34,6 @@ try {
diff --git a/ext/zlib/tests/gzeof_variation1.phpt b/ext/zlib/tests/gzeof_variation1.phpt
index 40e6899d6e583..fb4191fa7940a 100644
--- a/ext/zlib/tests/gzeof_variation1.phpt
+++ b/ext/zlib/tests/gzeof_variation1.phpt
@@ -24,4 +24,4 @@ unlink($filename);
+gzeof(): Argument #1 ($stream) must be an open stream resource
diff --git a/main/php_streams.h b/main/php_streams.h
index 80cb96951ee14..f534bc27285f1 100644
--- a/main/php_streams.h
+++ b/main/php_streams.h
@@ -287,11 +287,21 @@ END_EXTERN_C()
BEGIN_EXTERN_C()
-static zend_always_inline bool php_stream_zend_parse_arg_into_stream(zval *arg, php_stream **destination_stream_ptr, bool check_null)
-{
+static zend_always_inline bool php_stream_zend_parse_arg_into_stream(
+ zval *arg,
+ php_stream **destination_stream_ptr,
+ bool check_null,
+ uint32_t arg_num
+) {
if (EXPECTED(Z_TYPE_P(arg) == IS_RESOURCE)) {
- *destination_stream_ptr = (php_stream*)zend_fetch_resource2(Z_RES_P(arg), "stream", php_file_le_stream(), php_file_le_pstream());
- if (UNEXPECTED(*destination_stream_ptr == NULL)) {
+ zend_resource *res = Z_RES_P(arg);
+ /* We do not use zend_fetch_resource2() API,
+ * as we want to be able to specify the argument number in the type error */
+ if (EXPECTED(res->type == php_file_le_stream() || res->type == php_file_le_pstream())) {
+ *destination_stream_ptr = (php_stream*)res->ptr;
+ return true;
+ } else {
+ zend_argument_type_error(arg_num, "must be an open stream resource");
return false;
}
} else if (check_null && EXPECTED(Z_TYPE_P(arg) == IS_NULL)) {
@@ -304,7 +314,7 @@ static zend_always_inline bool php_stream_zend_parse_arg_into_stream(zval *arg,
#define PHP_Z_PARAM_STREAM_EX(destination_stream_ptr, check_null) \
Z_PARAM_PROLOGUE(0, 0); \
+ if (UNEXPECTED(!php_stream_zend_parse_arg_into_stream(_arg, &destination_stream_ptr, check_null, _i))) { \
_error_code = ZPP_ERROR_FAILURE; \
if (!EG(exception)) { \
_expected_type = check_null ? Z_EXPECTED_RESOURCE_OR_NULL : Z_EXPECTED_RESOURCE; \ | [
"-bzread(): supplied resource is not a valid stream resource",
"+bzerrstr(): Argument #1 ($bz) must be an open stream resource",
"-fgetc(): supplied resource is not a valid stream resource",
"+fclose(): Argument #1 ($stream) must be an open stream resource",
"-stream_get_meta_data(): supplied resource is not a valid stream resource",
"-gzeof(): supplied resource is not a valid stream resource",
"-\tif (UNEXPECTED(!php_stream_zend_parse_arg_into_stream(_arg, &destination_stream_ptr, check_null))) { \\"
] | [
8,
14,
429,
581,
600,
651,
687
] | {
"additions": 101,
"author": "Girgias",
"deletions": 98,
"html_url": "https://github.com/php/php-src/pull/18078",
"issue_id": 18078,
"merged_at": "2025-03-24T22:54:35Z",
"omission_probability": 0.1,
"pr_number": 18078,
"repo": "php/php-src",
"title": "streams: Indicate which argument fails the stream ZPP check",
"total_changes": 199
} |
788 | diff --git a/NEWS b/NEWS
index fcb849ef98a58..a5609377683ed 100644
--- a/NEWS
+++ b/NEWS
@@ -38,6 +38,8 @@ PHP NEWS
. Fixed bug GH-18033 (NULL-ptr dereference when using register_tick_function
in destructor). (nielsdos)
. Fixed bug GH-18026 (Improve "expecting token" error for ampersand). (ilutov)
+ . Added the (void) cast to indicate that not using a value is intentional.
+ (timwolla)
- Curl:
. Added curl_multi_get_handles(). (timwolla)
diff --git a/UPGRADING b/UPGRADING
index 274f45d8f401b..1f58e462e6715 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -106,6 +106,9 @@ PHP 8.5 UPGRADE NOTES
. Fatal Errors (such as an exceeded maximum execution time) now include a
backtrace.
RFC: https://wiki.php.net/rfc/error_backtraces_v2
+ . Added the (void) to indicate that not using a value is intentional. The
+ (void) cast does nothing by itself.
+ RFC: https://wiki.php.net/rfc/marking_return_value_as_important
- Curl:
. Added support for share handles that are persisted across multiple PHP
diff --git a/Zend/Optimizer/block_pass.c b/Zend/Optimizer/block_pass.c
index 6fcbd04f12af5..2b6d71c385457 100644
--- a/Zend/Optimizer/block_pass.c
+++ b/Zend/Optimizer/block_pass.c
@@ -274,7 +274,9 @@ static void zend_optimize_block(zend_basic_block *block, zend_op_array *op_array
* If it's not local, then the other blocks successors must also eventually either FREE or consume the temporary,
* hence removing the temporary is not safe in the general case, especially when other consumers are not FREE.
* A FREE may not be removed without also removing the source's result, because otherwise that would cause a memory leak. */
- if (opline->op1_type == IS_TMP_VAR) {
+ if (opline->extended_value == ZEND_FREE_VOID_CAST) {
+ /* Keep the ZEND_FREE opcode alive. */
+ } else if (opline->op1_type == IS_TMP_VAR) {
src = VAR_SOURCE(opline->op1);
if (src) {
switch (src->opcode) {
diff --git a/Zend/Optimizer/dce.c b/Zend/Optimizer/dce.c
index 414abe01f96ac..a00fd8bc6ad30 100644
--- a/Zend/Optimizer/dce.c
+++ b/Zend/Optimizer/dce.c
@@ -80,7 +80,6 @@ static inline bool may_have_side_effects(
case ZEND_IS_IDENTICAL:
case ZEND_IS_NOT_IDENTICAL:
case ZEND_QM_ASSIGN:
- case ZEND_FREE:
case ZEND_FE_FREE:
case ZEND_TYPE_CHECK:
case ZEND_DEFINED:
@@ -127,6 +126,8 @@ static inline bool may_have_side_effects(
case ZEND_ARRAY_KEY_EXISTS:
/* No side effects */
return 0;
+ case ZEND_FREE:
+ return opline->extended_value == ZEND_FREE_VOID_CAST;
case ZEND_ADD_ARRAY_ELEMENT:
/* TODO: We can't free two vars. Keep instruction alive. <?php [0, "$a" => "$b"]; */
if ((opline->op1_type & (IS_VAR|IS_TMP_VAR)) && (opline->op2_type & (IS_VAR|IS_TMP_VAR))) {
diff --git a/Zend/tests/type_casts/cast_to_void.phpt b/Zend/tests/type_casts/cast_to_void.phpt
new file mode 100644
index 0000000000000..cdbcffad519c9
--- /dev/null
+++ b/Zend/tests/type_casts/cast_to_void.phpt
@@ -0,0 +1,47 @@
+--TEST--
+casting different variables to void
+--FILE--
+<?php
+
+$r = fopen(__FILE__, "r");
+
+class test {
+ private $var1 = 1;
+ public $var2 = 2;
+ protected $var3 = 3;
+
+ function __toString() {
+ return "10";
+ }
+}
+
+$o = new test;
+
+$vars = array(
+ "string",
+ "",
+ "\0",
+ "8754456",
+ 9876545,
+ 0.10,
+ array(),
+ array(1,2,3),
+ false,
+ true,
+ NULL,
+ $r,
+ $o
+);
+
+foreach ($vars as $var) {
+ (void)$var;
+}
+
+// Cast literals to verify behavior for optimized const zvals
+(void)"foo";
+(void)["foo", "bar"];
+
+echo "Done\n";
+?>
+--EXPECTF--
+Done
diff --git a/Zend/tests/type_casts/cast_to_void_ast.phpt b/Zend/tests/type_casts/cast_to_void_ast.phpt
new file mode 100644
index 0000000000000..26911bddb7ebc
--- /dev/null
+++ b/Zend/tests/type_casts/cast_to_void_ast.phpt
@@ -0,0 +1,18 @@
+--TEST--
+(void) is included in AST printing
+--FILE--
+<?php
+
+try {
+ assert(false && function () {
+ (void) somefunc();
+ });
+} catch (Error $e) {
+ echo $e->getMessage(), "\n";
+}
+
+?>
+--EXPECT--
+assert(false && function () {
+ (void)somefunc();
+})
diff --git a/Zend/tests/type_casts/cast_to_void_destructor.phpt b/Zend/tests/type_casts/cast_to_void_destructor.phpt
new file mode 100644
index 0000000000000..027e4b77e5dda
--- /dev/null
+++ b/Zend/tests/type_casts/cast_to_void_destructor.phpt
@@ -0,0 +1,30 @@
+--TEST--
+casting to void destroys the value.
+--FILE--
+<?php
+
+class WithDestructor {
+ public function __destruct() {
+ echo __METHOD__, PHP_EOL;
+ }
+}
+
+function test(): WithDestructor {
+ return new WithDestructor();
+}
+
+function do_it(): void {
+ echo "Before", PHP_EOL;
+
+ (void)test();
+
+ echo "After", PHP_EOL;
+}
+
+do_it();
+
+?>
+--EXPECT--
+Before
+WithDestructor::__destruct
+After
diff --git a/Zend/tests/type_casts/cast_to_void_statement.phpt b/Zend/tests/type_casts/cast_to_void_statement.phpt
new file mode 100644
index 0000000000000..3262e1efd549c
--- /dev/null
+++ b/Zend/tests/type_casts/cast_to_void_statement.phpt
@@ -0,0 +1,11 @@
+--TEST--
+casting to void is a statement
+--FILE--
+<?php
+
+$tmp = (void)$dummy;
+
+echo "Done\n";
+?>
+--EXPECTF--
+Parse error: syntax error, unexpected token "(void)" in %s on line %d
diff --git a/Zend/zend_ast.c b/Zend/zend_ast.c
index 8b0a66fda8096..1ae7a0ef7a68e 100644
--- a/Zend/zend_ast.c
+++ b/Zend/zend_ast.c
@@ -2261,6 +2261,9 @@ static ZEND_COLD void zend_ast_export_ex(smart_str *str, zend_ast *ast, int prio
EMPTY_SWITCH_DEFAULT_CASE();
}
break;
+ case ZEND_AST_CAST_VOID:
+ PREFIX_OP("(void)", 240, 241);
+ break;
case ZEND_AST_EMPTY:
FUNC_OP("empty");
case ZEND_AST_ISSET:
diff --git a/Zend/zend_ast.h b/Zend/zend_ast.h
index d0dad8490c4e3..9348c35f6cc07 100644
--- a/Zend/zend_ast.h
+++ b/Zend/zend_ast.h
@@ -84,6 +84,7 @@ enum _zend_ast_kind {
ZEND_AST_UNARY_PLUS,
ZEND_AST_UNARY_MINUS,
ZEND_AST_CAST,
+ ZEND_AST_CAST_VOID,
ZEND_AST_EMPTY,
ZEND_AST_ISSET,
ZEND_AST_SILENCE,
diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c
index cd0ac6eb07b9c..1cba9ef221997 100644
--- a/Zend/zend_compile.c
+++ b/Zend/zend_compile.c
@@ -10589,6 +10589,26 @@ static void zend_compile_include_or_eval(znode *result, zend_ast *ast) /* {{{ */
}
/* }}} */
+static void zend_compile_void_cast(znode *result, zend_ast *ast)
+{
+ zend_ast *expr_ast = ast->child[0];
+ znode expr_node;
+ zend_op *opline;
+
+ zend_compile_expr(&expr_node, expr_ast);
+
+ switch (expr_node.op_type) {
+ case IS_TMP_VAR:
+ case IS_VAR:
+ opline = zend_emit_op(NULL, ZEND_FREE, &expr_node, NULL);
+ opline->extended_value = ZEND_FREE_VOID_CAST;
+ break;
+ case IS_CONST:
+ zend_do_free(&expr_node);
+ break;
+ }
+}
+
static void zend_compile_isset_or_empty(znode *result, zend_ast *ast) /* {{{ */
{
zend_ast *var_ast = ast->child[0];
@@ -11547,6 +11567,9 @@ static void zend_compile_stmt(zend_ast *ast) /* {{{ */
case ZEND_AST_THROW:
zend_compile_expr(NULL, ast);
break;
+ case ZEND_AST_CAST_VOID:
+ zend_compile_void_cast(NULL, ast);
+ break;
default:
{
znode result;
diff --git a/Zend/zend_compile.h b/Zend/zend_compile.h
index a7ee8f9327c54..224a68be749cb 100644
--- a/Zend/zend_compile.h
+++ b/Zend/zend_compile.h
@@ -1092,6 +1092,7 @@ ZEND_API zend_string *zend_type_to_string(zend_type type);
#define ZEND_FREE_ON_RETURN (1<<0)
#define ZEND_FREE_SWITCH (1<<1)
+#define ZEND_FREE_VOID_CAST (1<<2)
#define ZEND_SEND_BY_VAL 0u
#define ZEND_SEND_BY_REF 1u
diff --git a/Zend/zend_language_parser.y b/Zend/zend_language_parser.y
index 1f117d142c158..9483a83b4e955 100644
--- a/Zend/zend_language_parser.y
+++ b/Zend/zend_language_parser.y
@@ -217,6 +217,7 @@ static YYSIZE_T zend_yytnamerr(char*, const char*);
%token T_OBJECT_CAST "'(object)'"
%token T_BOOL_CAST "'(bool)'"
%token T_UNSET_CAST "'(unset)'"
+%token T_VOID_CAST "'(void)'"
%token T_OBJECT_OPERATOR "'->'"
%token T_NULLSAFE_OBJECT_OPERATOR "'?->'"
%token T_DOUBLE_ARROW "'=>'"
@@ -534,6 +535,7 @@ statement:
{ $$ = zend_ast_create(ZEND_AST_TRY, $3, $5, $6); }
| T_GOTO T_STRING ';' { $$ = zend_ast_create(ZEND_AST_GOTO, $2); }
| T_STRING ':' { $$ = zend_ast_create(ZEND_AST_LABEL, $1); }
+ | T_VOID_CAST expr ';' { $$ = zend_ast_create(ZEND_AST_CAST_VOID, $2); }
;
catch_list:
diff --git a/Zend/zend_language_scanner.l b/Zend/zend_language_scanner.l
index 7ae73875926eb..4c883b81c5f7d 100644
--- a/Zend/zend_language_scanner.l
+++ b/Zend/zend_language_scanner.l
@@ -1657,6 +1657,10 @@ OPTIONAL_WHITESPACE_OR_COMMENTS ({WHITESPACE}|{MULTI_LINE_COMMENT}|{SINGLE_LINE_
RETURN_TOKEN(T_UNSET_CAST);
}
+<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("void"){TABS_AND_SPACES}")" {
+ RETURN_TOKEN(T_VOID_CAST);
+}
+
<ST_IN_SCRIPTING>"eval" {
RETURN_TOKEN_WITH_IDENT(T_EVAL);
}
diff --git a/ext/tokenizer/tokenizer_data.c b/ext/tokenizer/tokenizer_data.c
index a046ab50e1498..a1e131032bcfb 100644
--- a/ext/tokenizer/tokenizer_data.c
+++ b/ext/tokenizer/tokenizer_data.c
@@ -153,6 +153,7 @@ char *get_token_type_name(int token_type)
case T_OBJECT_CAST: return "T_OBJECT_CAST";
case T_BOOL_CAST: return "T_BOOL_CAST";
case T_UNSET_CAST: return "T_UNSET_CAST";
+ case T_VOID_CAST: return "T_VOID_CAST";
case T_OBJECT_OPERATOR: return "T_OBJECT_OPERATOR";
case T_NULLSAFE_OBJECT_OPERATOR: return "T_NULLSAFE_OBJECT_OPERATOR";
case T_DOUBLE_ARROW: return "T_DOUBLE_ARROW";
diff --git a/ext/tokenizer/tokenizer_data.stub.php b/ext/tokenizer/tokenizer_data.stub.php
index 45f3c89f2de3a..c1e1fd254dfaa 100644
--- a/ext/tokenizer/tokenizer_data.stub.php
+++ b/ext/tokenizer/tokenizer_data.stub.php
@@ -642,6 +642,11 @@
* @cvalue T_UNSET_CAST
*/
const T_UNSET_CAST = UNKNOWN;
+/**
+ * @var int
+ * @cvalue T_VOID_CAST
+ */
+const T_VOID_CAST = UNKNOWN;
/**
* @var int
* @cvalue T_OBJECT_OPERATOR
diff --git a/ext/tokenizer/tokenizer_data_arginfo.h b/ext/tokenizer/tokenizer_data_arginfo.h
index 61f6ac1ec3659..9c488d19f1890 100644
--- a/ext/tokenizer/tokenizer_data_arginfo.h
+++ b/ext/tokenizer/tokenizer_data_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: d917cab61a2b436a16d2227cdb438add45e42d69 */
+ * Stub hash: 19d25d22098f46283b517352cbb302db962b50fd */
static void register_tokenizer_data_symbols(int module_number)
{
@@ -131,6 +131,7 @@ static void register_tokenizer_data_symbols(int module_number)
REGISTER_LONG_CONSTANT("T_OBJECT_CAST", T_OBJECT_CAST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_BOOL_CAST", T_BOOL_CAST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_UNSET_CAST", T_UNSET_CAST, CONST_PERSISTENT);
+ REGISTER_LONG_CONSTANT("T_VOID_CAST", T_VOID_CAST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_OBJECT_OPERATOR", T_OBJECT_OPERATOR, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_NULLSAFE_OBJECT_OPERATOR", T_NULLSAFE_OBJECT_OPERATOR, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_DOUBLE_ARROW", T_DOUBLE_ARROW, CONST_PERSISTENT);
| diff --git a/NEWS b/NEWS
index fcb849ef98a58..a5609377683ed 100644
--- a/NEWS
+++ b/NEWS
@@ -38,6 +38,8 @@ PHP NEWS
. Fixed bug GH-18033 (NULL-ptr dereference when using register_tick_function
in destructor). (nielsdos)
. Fixed bug GH-18026 (Improve "expecting token" error for ampersand). (ilutov)
+ . Added the (void) cast to indicate that not using a value is intentional.
+ (timwolla)
. Added curl_multi_get_handles(). (timwolla)
diff --git a/UPGRADING b/UPGRADING
index 274f45d8f401b..1f58e462e6715 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -106,6 +106,9 @@ PHP 8.5 UPGRADE NOTES
. Fatal Errors (such as an exceeded maximum execution time) now include a
backtrace.
RFC: https://wiki.php.net/rfc/error_backtraces_v2
+ . Added the (void) to indicate that not using a value is intentional. The
+ (void) cast does nothing by itself.
+ RFC: https://wiki.php.net/rfc/marking_return_value_as_important
. Added support for share handles that are persisted across multiple PHP
diff --git a/Zend/Optimizer/block_pass.c b/Zend/Optimizer/block_pass.c
index 6fcbd04f12af5..2b6d71c385457 100644
--- a/Zend/Optimizer/block_pass.c
+++ b/Zend/Optimizer/block_pass.c
@@ -274,7 +274,9 @@ static void zend_optimize_block(zend_basic_block *block, zend_op_array *op_array
* If it's not local, then the other blocks successors must also eventually either FREE or consume the temporary,
* hence removing the temporary is not safe in the general case, especially when other consumers are not FREE.
* A FREE may not be removed without also removing the source's result, because otherwise that would cause a memory leak. */
- if (opline->op1_type == IS_TMP_VAR) {
+ if (opline->extended_value == ZEND_FREE_VOID_CAST) {
+ /* Keep the ZEND_FREE opcode alive. */
+ } else if (opline->op1_type == IS_TMP_VAR) {
src = VAR_SOURCE(opline->op1);
if (src) {
switch (src->opcode) {
diff --git a/Zend/Optimizer/dce.c b/Zend/Optimizer/dce.c
index 414abe01f96ac..a00fd8bc6ad30 100644
--- a/Zend/Optimizer/dce.c
+++ b/Zend/Optimizer/dce.c
@@ -80,7 +80,6 @@ static inline bool may_have_side_effects(
case ZEND_IS_IDENTICAL:
case ZEND_IS_NOT_IDENTICAL:
case ZEND_QM_ASSIGN:
case ZEND_FE_FREE:
case ZEND_TYPE_CHECK:
case ZEND_DEFINED:
@@ -127,6 +126,8 @@ static inline bool may_have_side_effects(
case ZEND_ARRAY_KEY_EXISTS:
/* No side effects */
return 0;
+ case ZEND_FREE:
+ return opline->extended_value == ZEND_FREE_VOID_CAST;
case ZEND_ADD_ARRAY_ELEMENT:
/* TODO: We can't free two vars. Keep instruction alive. <?php [0, "$a" => "$b"]; */
if ((opline->op1_type & (IS_VAR|IS_TMP_VAR)) && (opline->op2_type & (IS_VAR|IS_TMP_VAR))) {
diff --git a/Zend/tests/type_casts/cast_to_void.phpt b/Zend/tests/type_casts/cast_to_void.phpt
index 0000000000000..cdbcffad519c9
+++ b/Zend/tests/type_casts/cast_to_void.phpt
@@ -0,0 +1,47 @@
+casting different variables to void
+class test {
+ private $var1 = 1;
+ public $var2 = 2;
+ protected $var3 = 3;
+ function __toString() {
+ return "10";
+ }
+$o = new test;
+$vars = array(
+ "string",
+ "",
+ "\0",
+ "8754456",
+ 0.10,
+ array(),
+ array(1,2,3),
+ false,
+ true,
+ NULL,
+ $r,
+ $o
+);
+foreach ($vars as $var) {
+// Cast literals to verify behavior for optimized const zvals
+(void)"foo";
+(void)["foo", "bar"];
+Done
diff --git a/Zend/tests/type_casts/cast_to_void_ast.phpt b/Zend/tests/type_casts/cast_to_void_ast.phpt
index 0000000000000..26911bddb7ebc
+++ b/Zend/tests/type_casts/cast_to_void_ast.phpt
@@ -0,0 +1,18 @@
+(void) is included in AST printing
+try {
+ assert(false && function () {
+ (void) somefunc();
+ });
+} catch (Error $e) {
+ echo $e->getMessage(), "\n";
+assert(false && function () {
+ (void)somefunc();
+})
diff --git a/Zend/tests/type_casts/cast_to_void_destructor.phpt b/Zend/tests/type_casts/cast_to_void_destructor.phpt
index 0000000000000..027e4b77e5dda
+++ b/Zend/tests/type_casts/cast_to_void_destructor.phpt
@@ -0,0 +1,30 @@
+casting to void destroys the value.
+class WithDestructor {
+ public function __destruct() {
+ echo __METHOD__, PHP_EOL;
+function test(): WithDestructor {
+ return new WithDestructor();
+function do_it(): void {
+ echo "Before", PHP_EOL;
+ (void)test();
+ echo "After", PHP_EOL;
+do_it();
+Before
+WithDestructor::__destruct
+After
diff --git a/Zend/tests/type_casts/cast_to_void_statement.phpt b/Zend/tests/type_casts/cast_to_void_statement.phpt
index 0000000000000..3262e1efd549c
+++ b/Zend/tests/type_casts/cast_to_void_statement.phpt
@@ -0,0 +1,11 @@
+casting to void is a statement
+$tmp = (void)$dummy;
+Parse error: syntax error, unexpected token "(void)" in %s on line %d
diff --git a/Zend/zend_ast.c b/Zend/zend_ast.c
index 8b0a66fda8096..1ae7a0ef7a68e 100644
--- a/Zend/zend_ast.c
+++ b/Zend/zend_ast.c
@@ -2261,6 +2261,9 @@ static ZEND_COLD void zend_ast_export_ex(smart_str *str, zend_ast *ast, int prio
EMPTY_SWITCH_DEFAULT_CASE();
}
+ PREFIX_OP("(void)", 240, 241);
case ZEND_AST_EMPTY:
FUNC_OP("empty");
case ZEND_AST_ISSET:
diff --git a/Zend/zend_ast.h b/Zend/zend_ast.h
index d0dad8490c4e3..9348c35f6cc07 100644
--- a/Zend/zend_ast.h
+++ b/Zend/zend_ast.h
@@ -84,6 +84,7 @@ enum _zend_ast_kind {
ZEND_AST_UNARY_PLUS,
ZEND_AST_UNARY_MINUS,
ZEND_AST_CAST,
+ ZEND_AST_CAST_VOID,
ZEND_AST_EMPTY,
ZEND_AST_ISSET,
ZEND_AST_SILENCE,
diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c
index cd0ac6eb07b9c..1cba9ef221997 100644
--- a/Zend/zend_compile.c
+++ b/Zend/zend_compile.c
@@ -10589,6 +10589,26 @@ static void zend_compile_include_or_eval(znode *result, zend_ast *ast) /* {{{ */
/* }}} */
+static void zend_compile_void_cast(znode *result, zend_ast *ast)
+{
+ zend_ast *expr_ast = ast->child[0];
+ znode expr_node;
+ zend_op *opline;
+ zend_compile_expr(&expr_node, expr_ast);
+ switch (expr_node.op_type) {
+ case IS_TMP_VAR:
+ case IS_VAR:
+ case IS_CONST:
+ zend_do_free(&expr_node);
static void zend_compile_isset_or_empty(znode *result, zend_ast *ast) /* {{{ */
zend_ast *var_ast = ast->child[0];
@@ -11547,6 +11567,9 @@ static void zend_compile_stmt(zend_ast *ast) /* {{{ */
case ZEND_AST_THROW:
zend_compile_expr(NULL, ast);
+ zend_compile_void_cast(NULL, ast);
default:
{
znode result;
diff --git a/Zend/zend_compile.h b/Zend/zend_compile.h
index a7ee8f9327c54..224a68be749cb 100644
--- a/Zend/zend_compile.h
+++ b/Zend/zend_compile.h
@@ -1092,6 +1092,7 @@ ZEND_API zend_string *zend_type_to_string(zend_type type);
#define ZEND_FREE_ON_RETURN (1<<0)
#define ZEND_FREE_SWITCH (1<<1)
+#define ZEND_FREE_VOID_CAST (1<<2)
#define ZEND_SEND_BY_VAL 0u
#define ZEND_SEND_BY_REF 1u
diff --git a/Zend/zend_language_parser.y b/Zend/zend_language_parser.y
index 1f117d142c158..9483a83b4e955 100644
--- a/Zend/zend_language_parser.y
+++ b/Zend/zend_language_parser.y
@@ -217,6 +217,7 @@ static YYSIZE_T zend_yytnamerr(char*, const char*);
%token T_OBJECT_CAST "'(object)'"
%token T_BOOL_CAST "'(bool)'"
%token T_UNSET_CAST "'(unset)'"
+%token T_VOID_CAST "'(void)'"
%token T_OBJECT_OPERATOR "'->'"
%token T_NULLSAFE_OBJECT_OPERATOR "'?->'"
%token T_DOUBLE_ARROW "'=>'"
@@ -534,6 +535,7 @@ statement:
{ $$ = zend_ast_create(ZEND_AST_TRY, $3, $5, $6); }
| T_GOTO T_STRING ';' { $$ = zend_ast_create(ZEND_AST_GOTO, $2); }
| T_STRING ':' { $$ = zend_ast_create(ZEND_AST_LABEL, $1); }
+ | T_VOID_CAST expr ';' { $$ = zend_ast_create(ZEND_AST_CAST_VOID, $2); }
;
catch_list:
diff --git a/Zend/zend_language_scanner.l b/Zend/zend_language_scanner.l
index 7ae73875926eb..4c883b81c5f7d 100644
--- a/Zend/zend_language_scanner.l
+++ b/Zend/zend_language_scanner.l
@@ -1657,6 +1657,10 @@ OPTIONAL_WHITESPACE_OR_COMMENTS ({WHITESPACE}|{MULTI_LINE_COMMENT}|{SINGLE_LINE_
RETURN_TOKEN(T_UNSET_CAST);
+<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("void"){TABS_AND_SPACES}")" {
+ RETURN_TOKEN(T_VOID_CAST);
<ST_IN_SCRIPTING>"eval" {
RETURN_TOKEN_WITH_IDENT(T_EVAL);
diff --git a/ext/tokenizer/tokenizer_data.c b/ext/tokenizer/tokenizer_data.c
index a046ab50e1498..a1e131032bcfb 100644
--- a/ext/tokenizer/tokenizer_data.c
+++ b/ext/tokenizer/tokenizer_data.c
@@ -153,6 +153,7 @@ char *get_token_type_name(int token_type)
case T_OBJECT_CAST: return "T_OBJECT_CAST";
case T_BOOL_CAST: return "T_BOOL_CAST";
case T_UNSET_CAST: return "T_UNSET_CAST";
+ case T_VOID_CAST: return "T_VOID_CAST";
case T_OBJECT_OPERATOR: return "T_OBJECT_OPERATOR";
case T_NULLSAFE_OBJECT_OPERATOR: return "T_NULLSAFE_OBJECT_OPERATOR";
case T_DOUBLE_ARROW: return "T_DOUBLE_ARROW";
diff --git a/ext/tokenizer/tokenizer_data.stub.php b/ext/tokenizer/tokenizer_data.stub.php
index 45f3c89f2de3a..c1e1fd254dfaa 100644
--- a/ext/tokenizer/tokenizer_data.stub.php
+++ b/ext/tokenizer/tokenizer_data.stub.php
@@ -642,6 +642,11 @@
* @cvalue T_UNSET_CAST
*/
const T_UNSET_CAST = UNKNOWN;
+ * @var int
+ * @cvalue T_VOID_CAST
+ */
+const T_VOID_CAST = UNKNOWN;
/**
* @var int
* @cvalue T_OBJECT_OPERATOR
diff --git a/ext/tokenizer/tokenizer_data_arginfo.h b/ext/tokenizer/tokenizer_data_arginfo.h
index 61f6ac1ec3659..9c488d19f1890 100644
--- a/ext/tokenizer/tokenizer_data_arginfo.h
+++ b/ext/tokenizer/tokenizer_data_arginfo.h
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
- * Stub hash: d917cab61a2b436a16d2227cdb438add45e42d69 */
+ * Stub hash: 19d25d22098f46283b517352cbb302db962b50fd */
static void register_tokenizer_data_symbols(int module_number)
@@ -131,6 +131,7 @@ static void register_tokenizer_data_symbols(int module_number)
REGISTER_LONG_CONSTANT("T_OBJECT_CAST", T_OBJECT_CAST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_BOOL_CAST", T_BOOL_CAST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_UNSET_CAST", T_UNSET_CAST, CONST_PERSISTENT);
+ REGISTER_LONG_CONSTANT("T_VOID_CAST", T_VOID_CAST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_OBJECT_OPERATOR", T_OBJECT_OPERATOR, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_NULLSAFE_OBJECT_OPERATOR", T_NULLSAFE_OBJECT_OPERATOR, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("T_DOUBLE_ARROW", T_DOUBLE_ARROW, CONST_PERSISTENT); | [
"-\t\tcase ZEND_FREE:",
"+$r = fopen(__FILE__, \"r\");",
"+ 9876545,",
"+ (void)$var;",
"+\t\t\topline = zend_emit_op(NULL, ZEND_FREE, &expr_node, NULL);",
"+\t\t\topline->extended_value = ZEND_FREE_VOID_CAST;",
"+/**"
] | [
50,
74,
93,
105,
238,
239,
327
] | {
"additions": 158,
"author": "TimWolla",
"deletions": 3,
"html_url": "https://github.com/php/php-src/pull/18115",
"issue_id": 18115,
"merged_at": "2025-03-24T18:35:31Z",
"omission_probability": 0.1,
"pr_number": 18115,
"repo": "php/php-src",
"title": "Add `(void)` cast",
"total_changes": 161
} |
789 | diff --git a/examples/server/server.cpp b/examples/server/server.cpp
index 1bf1ee876b40f..d87bda1a0d5af 100644
--- a/examples/server/server.cpp
+++ b/examples/server/server.cpp
@@ -3907,6 +3907,21 @@ int main(int argc, char ** argv) {
res_ok(res, {{ "success", true }});
};
+ const auto handle_api_show = [&ctx_server, &res_ok](const httplib::Request &, httplib::Response & res) {
+ json data = {
+ {
+ "template", common_chat_templates_source(ctx_server.chat_templates.get()),
+ },
+ {
+ "model_info", {
+ { "llama.context_length", ctx_server.slots.back().n_ctx, },
+ }
+ },
+ };
+
+ res_ok(res, data);
+ };
+
// handle completion-like requests (completion, chat, infill)
// we can optionally provide a custom format for partial results and final results
const auto handle_completions_impl = [&ctx_server, &res_error, &res_ok](
@@ -4471,6 +4486,7 @@ int main(int argc, char ** argv) {
svr->Get ("/metrics", handle_metrics);
svr->Get ("/props", handle_props);
svr->Post("/props", handle_props_change);
+ svr->Post("/api/show", handle_api_show);
svr->Get ("/models", handle_models); // public endpoint (no API key check)
svr->Get ("/v1/models", handle_models); // public endpoint (no API key check)
svr->Post("/completion", handle_completions); // legacy
| diff --git a/examples/server/server.cpp b/examples/server/server.cpp
index 1bf1ee876b40f..d87bda1a0d5af 100644
--- a/examples/server/server.cpp
+++ b/examples/server/server.cpp
@@ -3907,6 +3907,21 @@ int main(int argc, char ** argv) {
res_ok(res, {{ "success", true }});
};
+ "template", common_chat_templates_source(ctx_server.chat_templates.get()),
+ "model_info", {
+ { "llama.context_length", ctx_server.slots.back().n_ctx, },
+ }
+ };
+ res_ok(res, data);
+ };
// handle completion-like requests (completion, chat, infill)
// we can optionally provide a custom format for partial results and final results
const auto handle_completions_impl = [&ctx_server, &res_error, &res_ok](
@@ -4471,6 +4486,7 @@ int main(int argc, char ** argv) {
svr->Get ("/metrics", handle_metrics);
svr->Get ("/props", handle_props);
svr->Post("/props", handle_props_change);
+ svr->Post("/api/show", handle_api_show);
svr->Get ("/models", handle_models); // public endpoint (no API key check)
svr->Get ("/v1/models", handle_models); // public endpoint (no API key check)
svr->Post("/completion", handle_completions); // legacy | [
"+ const auto handle_api_show = [&ctx_server, &res_ok](const httplib::Request &, httplib::Response & res) {",
"+ json data = {"
] | [
8,
9
] | {
"additions": 16,
"author": "ggerganov",
"deletions": 0,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/12896",
"issue_id": 12896,
"merged_at": "2025-04-11T20:37:41Z",
"omission_probability": 0.1,
"pr_number": 12896,
"repo": "ggml-org/llama.cpp",
"title": "server : add VSCode's Github Copilot Chat support",
"total_changes": 16
} |
790 | diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 983385f86d494..a52b6850b465d 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -469,8 +469,7 @@ ggml_tensor * llama_context::build_rope_shift(
ggml_tensor * shift,
ggml_tensor * factors,
float freq_base,
- float freq_scale,
- ggml_backend_buffer * bbuf) const {
+ float freq_scale) const {
const auto & n_ctx_orig = cparams.n_ctx_orig_yarn;
const auto & yarn_ext_factor = cparams.yarn_ext_factor;
@@ -492,17 +491,7 @@ ggml_tensor * llama_context::build_rope_shift(
// dequantize to f32 -> RoPE -> quantize back
tmp = ggml_cast(ctx0, cur, GGML_TYPE_F32);
- if (bbuf) {
- for (const auto & backend : backends) {
- // Figure out which backend KV cache belongs to
- if (ggml_backend_supports_buft(backend.get(), ggml_backend_buffer_get_type(bbuf))) {
- ggml_backend_sched_set_tensor_backend(sched.get(), tmp, backend.get());
- break;
- }
- }
- }
-
- tmp = ggml_rope_ext_inplace(ctx0, tmp,
+ tmp = ggml_rope_ext(ctx0, tmp,
shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
@@ -582,7 +571,7 @@ llm_graph_result_ptr llama_context::build_kv_self_shift(
ggml_row_size(kv_self->k_l[il]->type, n_embd_k_gqa),
0);
- ggml_tensor * cur = build_rope_shift(ctx0, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l, kv_self->k_l[il]->buffer);
+ ggml_tensor * cur = build_rope_shift(ctx0, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l);
ggml_build_forward_expand(gf, cur);
}
diff --git a/src/llama-context.h b/src/llama-context.h
index 04facb544cb1a..5457f077c15bf 100644
--- a/src/llama-context.h
+++ b/src/llama-context.h
@@ -170,8 +170,7 @@ struct llama_context {
ggml_tensor * shift,
ggml_tensor * factors,
float freq_base,
- float freq_scale,
- ggml_backend_buffer * bbuf) const;
+ float freq_scale) const;
llm_graph_result_ptr build_kv_self_shift(
ggml_context * ctx0,
| diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 983385f86d494..a52b6850b465d 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -469,8 +469,7 @@ ggml_tensor * llama_context::build_rope_shift(
const auto & n_ctx_orig = cparams.n_ctx_orig_yarn;
const auto & yarn_ext_factor = cparams.yarn_ext_factor;
@@ -492,17 +491,7 @@ ggml_tensor * llama_context::build_rope_shift(
// dequantize to f32 -> RoPE -> quantize back
tmp = ggml_cast(ctx0, cur, GGML_TYPE_F32);
- if (bbuf) {
- for (const auto & backend : backends) {
- if (ggml_backend_supports_buft(backend.get(), ggml_backend_buffer_get_type(bbuf))) {
- ggml_backend_sched_set_tensor_backend(sched.get(), tmp, backend.get());
- break;
- }
- }
- }
-
- tmp = ggml_rope_ext_inplace(ctx0, tmp,
+ tmp = ggml_rope_ext(ctx0, tmp,
shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
@@ -582,7 +571,7 @@ llm_graph_result_ptr llama_context::build_kv_self_shift(
ggml_row_size(kv_self->k_l[il]->type, n_embd_k_gqa),
0);
+ ggml_tensor * cur = build_rope_shift(ctx0, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l);
ggml_build_forward_expand(gf, cur);
}
diff --git a/src/llama-context.h b/src/llama-context.h
index 04facb544cb1a..5457f077c15bf 100644
--- a/src/llama-context.h
+++ b/src/llama-context.h
@@ -170,8 +170,7 @@ struct llama_context {
- ggml_backend_buffer * bbuf) const;
+ float freq_scale) const;
llm_graph_result_ptr build_kv_self_shift(
ggml_context * ctx0, | [
"- ggml_backend_buffer * bbuf) const {",
"+ float freq_scale) const {",
"- // Figure out which backend KV cache belongs to",
"- ggml_tensor * cur = build_rope_shift(ctx0, k, inp->k_shift, rope_factors, freq_base_l, freq_scale_l, kv_self->k_l[il]->buffer);"
] | [
9,
10,
20,
37
] | {
"additions": 4,
"author": "slaren",
"deletions": 16,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/13113",
"issue_id": 13113,
"merged_at": "2025-04-25T17:40:11Z",
"omission_probability": 0.1,
"pr_number": 13113,
"repo": "ggml-org/llama.cpp",
"title": "llama : fix K-shift with quantized K and BLAS backend",
"total_changes": 20
} |
791 | diff --git a/examples/llava/clip.cpp b/examples/llava/clip.cpp
index 4eec4a2646798..5c858a167b021 100644
--- a/examples/llava/clip.cpp
+++ b/examples/llava/clip.cpp
@@ -556,15 +556,15 @@ static ggml_cgraph * clip_image_build_graph_siglip(clip_ctx * ctx, const clip_im
}
// implementation of the 2D RoPE without adding a new op in ggml
+// this is not efficient (use double the memory), but works on all backends
+// TODO: there was a more efficient which relies on ggml_view and ggml_rope_ext_inplace, but the rope inplace does not work well with non-contiguous tensors ; we should fix that and revert back to the original implementation in https://github.com/ggml-org/llama.cpp/pull/13065
static ggml_tensor * build_rope_2d(
- ggml_cgraph * gf,
ggml_context * ctx0,
ggml_tensor * cur,
ggml_tensor * pos_h,
ggml_tensor * pos_w,
const float freq_base
) {
- ggml_tensor * tmp;
const int64_t n_dim = cur->ne[0];
const int64_t n_head = cur->ne[1];
const int64_t n_pos = cur->ne[2];
@@ -573,18 +573,23 @@ static ggml_tensor * build_rope_2d(
// we will have a list of 4 inv_freq: 1e-0, 1e-1, 1e-2, 1e-3
// first half of cur will use 1e-0, 1e-2 (even)
// second half of cur will use 1e-1, 1e-3 (odd)
- //
- // for the first half, the trick here is to rotate n_dim/2, so inv_freq will be even
+ // the trick here is to rotate just half of n_dim, so inv_freq will automatically be even
// ^ don't ask me why, it's math! -2(2i) / n_dim == -2i / (n_dim/2)
// then for the second half, we use freq_scale to shift the inv_freq
// ^ why? replace (2i) with (2i+1) in the above equation
const float freq_scale_odd = std::pow(freq_base, (float)-2/n_dim);
// first half
+ ggml_tensor * first;
{
- cur = ggml_rope_ext_inplace(
+ first = ggml_view_3d(ctx0, cur,
+ n_dim/2, n_head, n_pos,
+ ggml_row_size(cur->type, n_dim),
+ ggml_row_size(cur->type, n_dim*n_head),
+ 0);
+ first = ggml_rope_ext(
ctx0,
- cur,
+ first,
pos_h, // positions
nullptr, // freq factors
n_dim/2, // n_dims
@@ -594,15 +599,17 @@ static ggml_tensor * build_rope_2d(
}
// second half
+ ggml_tensor * second;
{
- tmp = ggml_view_3d(ctx0, cur,
+ second = ggml_view_3d(ctx0, cur,
n_dim/2, n_head, n_pos,
ggml_row_size(cur->type, n_dim),
ggml_row_size(cur->type, n_dim*n_head),
n_dim/2 * ggml_element_size(cur));
- tmp = ggml_rope_ext_inplace(
+ second = ggml_cont(ctx0, second); // copy, because ggml_rope don't play well with non-contiguous tensors
+ second = ggml_rope_ext(
ctx0,
- tmp,
+ second,
pos_w, // positions
nullptr, // freq factors
n_dim/2, // n_dims
@@ -610,10 +617,9 @@ static ggml_tensor * build_rope_2d(
freq_scale_odd,
0.0f, 1.0f, 0.0f, 0.0f
);
- // calculate inplace (modify cur directly)
- ggml_build_forward_expand(gf, tmp);
}
+ cur = ggml_concat(ctx0, first, second, 0);
return cur;
}
@@ -682,13 +688,13 @@ static ggml_cgraph * clip_image_build_graph_pixtral(clip_ctx * ctx, const clip_i
struct ggml_tensor * Q = ggml_mul_mat(ctx0, model.layers[il].q_w, cur);
Q = ggml_reshape_3d(ctx0, Q, d_head, n_head, num_patches);
- Q = build_rope_2d(gf, ctx0, Q, pos_h, pos_w, hparams.rope_theta);
+ Q = build_rope_2d(ctx0, Q, pos_h, pos_w, hparams.rope_theta);
Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
struct ggml_tensor * K = ggml_mul_mat(ctx0, model.layers[il].k_w, cur);
K = ggml_reshape_3d(ctx0, K, d_head, n_head, num_patches);
- K = build_rope_2d(gf, ctx0, K, pos_h, pos_w, hparams.rope_theta);
+ K = build_rope_2d(ctx0, K, pos_h, pos_w, hparams.rope_theta);
K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
struct ggml_tensor * V = ggml_mul_mat(ctx0, model.layers[il].v_w, cur);
@@ -2804,10 +2810,15 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
const auto & model = ctx->vision_model;
const auto & hparams = model.hparams;
+ // TODO @ngxson : this is ugly, need to refactor later
+ bool support_dynamic_size = ctx->has_minicpmv_projector
+ || ctx->has_qwen2vl_merger
+ || ctx->proj_type == PROJECTOR_TYPE_PIXTRAL;
+
const int image_size = hparams.image_size;
int image_size_width = image_size;
int image_size_height = image_size;
- if (ctx->has_minicpmv_projector | ctx->has_qwen2vl_merger) {
+ if (support_dynamic_size) {
image_size_width = imgs.entries[0]->nx;
image_size_height = imgs.entries[0]->ny;
}
@@ -2819,9 +2830,20 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
{
struct ggml_tensor * inp_raw = ggml_graph_get_tensor(gf, "inp_raw");
- float * data = (float *)malloc(ggml_nbytes(inp_raw));
+ std::vector<float> inp_data(ggml_nelements(inp_raw));
+ float * data = inp_data.data();
+
+ // layout of data (note: the channel dim is unrolled to better visualize the layout):
+ //
+ // ┌──W──┐
+ // │ H │ channel = R
+ // ├─────┤ │
+ // │ H │ channel = G
+ // ├─────┤ │
+ // │ H │ channel = B
+ // └─────┘ │
+ // ──────┘ x B
- // TODO @ngxson : this whole code block is ugly, will need to be refactored
for (size_t i = 0; i < imgs.entries.size(); i++) {
const int nx = imgs.entries[i]->nx;
const int ny = imgs.entries[i]->ny;
@@ -2836,17 +2858,19 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
const int n = nx * ny;
for (int b = 0; b < batch_size; b++) {
- for (int k = 0; k < 3; k++) {
- for (int y = 0; y < ny; y++) {
- for (int x = 0; x < nx; x++) {
- data[(b * 3 * n) + k * n + y * nx + x] = imgs.entries[b]->buf[3 * (y * nx + x) + k];
- }
+ float * batch_entry = data + b * (3*n);
+ for (int y = 0; y < ny; y++) {
+ for (int x = 0; x < nx; x++) {
+ size_t base_src = 3*(y * nx + x); // idx of the first channel
+ size_t base_dst = y * nx + x; // idx of the first channel
+ batch_entry[ base_dst] = imgs.entries[b]->buf[base_src ];
+ batch_entry[1*n + base_dst] = imgs.entries[b]->buf[base_src + 1];
+ batch_entry[2*n + base_dst] = imgs.entries[b]->buf[base_src + 2];
}
}
}
}
ggml_backend_tensor_set(inp_raw, data, 0, ggml_nbytes(inp_raw));
- free(data);
}
if (ctx->has_minicpmv_projector) {
{
diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp
index 61751755b317b..d70acb7719435 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -2606,6 +2606,8 @@ struct test_rope : public test_case {
} else {
out = ggml_rope_ext_back(ctx, a, pos, freq, n_dims, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
}
+
+ // TODO: add test with a non-contiguous view as input ; this case is needed for build_rope_2d in clip.cpp
}
ggml_set_name(out, "out");
| diff --git a/examples/llava/clip.cpp b/examples/llava/clip.cpp
index 4eec4a2646798..5c858a167b021 100644
--- a/examples/llava/clip.cpp
+++ b/examples/llava/clip.cpp
@@ -556,15 +556,15 @@ static ggml_cgraph * clip_image_build_graph_siglip(clip_ctx * ctx, const clip_im
// implementation of the 2D RoPE without adding a new op in ggml
+// this is not efficient (use double the memory), but works on all backends
+// TODO: there was a more efficient which relies on ggml_view and ggml_rope_ext_inplace, but the rope inplace does not work well with non-contiguous tensors ; we should fix that and revert back to the original implementation in https://github.com/ggml-org/llama.cpp/pull/13065
static ggml_tensor * build_rope_2d(
- ggml_cgraph * gf,
ggml_context * ctx0,
ggml_tensor * cur,
ggml_tensor * pos_h,
ggml_tensor * pos_w,
const float freq_base
) {
const int64_t n_dim = cur->ne[0];
const int64_t n_head = cur->ne[1];
const int64_t n_pos = cur->ne[2];
@@ -573,18 +573,23 @@ static ggml_tensor * build_rope_2d(
// we will have a list of 4 inv_freq: 1e-0, 1e-1, 1e-2, 1e-3
// first half of cur will use 1e-0, 1e-2 (even)
// second half of cur will use 1e-1, 1e-3 (odd)
- //
+ // the trick here is to rotate just half of n_dim, so inv_freq will automatically be even
// ^ don't ask me why, it's math! -2(2i) / n_dim == -2i / (n_dim/2)
// then for the second half, we use freq_scale to shift the inv_freq
// ^ why? replace (2i) with (2i+1) in the above equation
const float freq_scale_odd = std::pow(freq_base, (float)-2/n_dim);
// first half
+ ggml_tensor * first;
- cur = ggml_rope_ext_inplace(
+ first = ggml_view_3d(ctx0, cur,
+ n_dim/2, n_head, n_pos,
+ ggml_row_size(cur->type, n_dim),
+ ggml_row_size(cur->type, n_dim*n_head),
+ 0);
+ first = ggml_rope_ext(
+ first,
pos_h, // positions
@@ -594,15 +599,17 @@ static ggml_tensor * build_rope_2d(
// second half
+ ggml_tensor * second;
- tmp = ggml_view_3d(ctx0, cur,
+ second = ggml_view_3d(ctx0, cur,
n_dim/2, n_head, n_pos,
ggml_row_size(cur->type, n_dim),
ggml_row_size(cur->type, n_dim*n_head),
n_dim/2 * ggml_element_size(cur));
- tmp = ggml_rope_ext_inplace(
+ second = ggml_cont(ctx0, second); // copy, because ggml_rope don't play well with non-contiguous tensors
+ second = ggml_rope_ext(
- tmp,
+ second,
pos_w, // positions
@@ -610,10 +617,9 @@ static ggml_tensor * build_rope_2d(
freq_scale_odd,
0.0f, 1.0f, 0.0f, 0.0f
);
- // calculate inplace (modify cur directly)
- ggml_build_forward_expand(gf, tmp);
+ cur = ggml_concat(ctx0, first, second, 0);
return cur;
@@ -682,13 +688,13 @@ static ggml_cgraph * clip_image_build_graph_pixtral(clip_ctx * ctx, const clip_i
struct ggml_tensor * Q = ggml_mul_mat(ctx0, model.layers[il].q_w, cur);
Q = ggml_reshape_3d(ctx0, Q, d_head, n_head, num_patches);
- Q = build_rope_2d(gf, ctx0, Q, pos_h, pos_w, hparams.rope_theta);
+ Q = build_rope_2d(ctx0, Q, pos_h, pos_w, hparams.rope_theta);
Q = ggml_cont(ctx0, ggml_permute(ctx0, Q, 0, 2, 1, 3));
struct ggml_tensor * K = ggml_mul_mat(ctx0, model.layers[il].k_w, cur);
K = ggml_reshape_3d(ctx0, K, d_head, n_head, num_patches);
- K = build_rope_2d(gf, ctx0, K, pos_h, pos_w, hparams.rope_theta);
K = ggml_cont(ctx0, ggml_permute(ctx0, K, 0, 2, 1, 3));
struct ggml_tensor * V = ggml_mul_mat(ctx0, model.layers[il].v_w, cur);
@@ -2804,10 +2810,15 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
const auto & model = ctx->vision_model;
const auto & hparams = model.hparams;
+ // TODO @ngxson : this is ugly, need to refactor later
+ bool support_dynamic_size = ctx->has_minicpmv_projector
+ || ctx->has_qwen2vl_merger
+ || ctx->proj_type == PROJECTOR_TYPE_PIXTRAL;
const int image_size = hparams.image_size;
int image_size_width = image_size;
int image_size_height = image_size;
- if (ctx->has_minicpmv_projector | ctx->has_qwen2vl_merger) {
+ if (support_dynamic_size) {
image_size_width = imgs.entries[0]->nx;
image_size_height = imgs.entries[0]->ny;
@@ -2819,9 +2830,20 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
struct ggml_tensor * inp_raw = ggml_graph_get_tensor(gf, "inp_raw");
- float * data = (float *)malloc(ggml_nbytes(inp_raw));
+ std::vector<float> inp_data(ggml_nelements(inp_raw));
+ float * data = inp_data.data();
+ // layout of data (note: the channel dim is unrolled to better visualize the layout):
+ //
+ // │ H │ channel = R
+ // │ H │ channel = B
+ // ──────┘ x B
- // TODO @ngxson : this whole code block is ugly, will need to be refactored
for (size_t i = 0; i < imgs.entries.size(); i++) {
const int nx = imgs.entries[i]->nx;
const int ny = imgs.entries[i]->ny;
@@ -2836,17 +2858,19 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
const int n = nx * ny;
for (int b = 0; b < batch_size; b++) {
- for (int k = 0; k < 3; k++) {
- for (int y = 0; y < ny; y++) {
- for (int x = 0; x < nx; x++) {
- data[(b * 3 * n) + k * n + y * nx + x] = imgs.entries[b]->buf[3 * (y * nx + x) + k];
- }
+ float * batch_entry = data + b * (3*n);
+ for (int y = 0; y < ny; y++) {
+ for (int x = 0; x < nx; x++) {
+ size_t base_dst = y * nx + x; // idx of the first channel
+ batch_entry[ base_dst] = imgs.entries[b]->buf[base_src ];
+ batch_entry[1*n + base_dst] = imgs.entries[b]->buf[base_src + 1];
+ batch_entry[2*n + base_dst] = imgs.entries[b]->buf[base_src + 2];
}
}
ggml_backend_tensor_set(inp_raw, data, 0, ggml_nbytes(inp_raw));
- free(data);
if (ctx->has_minicpmv_projector) {
{
diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp
index 61751755b317b..d70acb7719435 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -2606,6 +2606,8 @@ struct test_rope : public test_case {
} else {
out = ggml_rope_ext_back(ctx, a, pos, freq, n_dims, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
+ // TODO: add test with a non-contiguous view as input ; this case is needed for build_rope_2d in clip.cpp
ggml_set_name(out, "out"); | [
"- ggml_tensor * tmp;",
"- // for the first half, the trick here is to rotate n_dim/2, so inv_freq will be even",
"- cur,",
"+ K = build_rope_2d(ctx0, K, pos_h, pos_w, hparams.rope_theta);",
"+ // ┌──W──┐",
"+ // │ H │ channel = G",
"+ // └─────┘ │",
"+ size_t base_src = 3*(y * nx + x); // idx of the first channel"
] | [
18,
27,
45,
95,
126,
129,
132,
151
] | {
"additions": 48,
"author": "ngxson",
"deletions": 22,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/13097",
"issue_id": 13097,
"merged_at": "2025-04-25T12:31:42Z",
"omission_probability": 0.1,
"pr_number": 13097,
"repo": "ggml-org/llama.cpp",
"title": "clip : fix pixtral on some GPU backends",
"total_changes": 70
} |
792 | diff --git a/ggml/src/ggml-sycl/common.hpp b/ggml/src/ggml-sycl/common.hpp
index 3e1ceeaa49486..a8187b0a9187f 100644
--- a/ggml/src/ggml-sycl/common.hpp
+++ b/ggml/src/ggml-sycl/common.hpp
@@ -313,7 +313,6 @@ struct ggml_backend_sycl_context {
int device;
std::string name;
optimize_feature opt_feature;
- bool optimized_graph=false;
queue_ptr qptrs[GGML_SYCL_MAX_DEVICES][GGML_SYCL_MAX_STREAMS] = { { nullptr } };
diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp
index 4d2fda0bfa6ae..22927338bda42 100644
--- a/ggml/src/ggml-sycl/ggml-sycl.cpp
+++ b/ggml/src/ggml-sycl/ggml-sycl.cpp
@@ -192,7 +192,7 @@ static void ggml_check_sycl() try {
if (!initialized) {
g_ggml_sycl_debug = get_sycl_env("GGML_SYCL_DEBUG", 0);
- g_ggml_sycl_disable_optimize= get_sycl_env("GGML_SYCL_DISABLE_OPT", 1);
+ g_ggml_sycl_disable_optimize= get_sycl_env("GGML_SYCL_DISABLE_OPT", 0);
g_ggml_sycl_disable_graph = get_sycl_env("GGML_SYCL_DISABLE_GRAPH", 1);
GGML_SYCL_DEBUG("[SYCL] call ggml_check_sycl\n");
GGML_LOG_INFO("Running with Environment Variables:\n");
@@ -2863,6 +2863,64 @@ static bool ggml_sycl_supports_dmmv(enum ggml_type type) {
}
}
+static void reorder_qw(char *data_device, const int ncols, const int nrows,
+ size_t size, size_t offset, dpct::queue_ptr stream) {
+ auto tmp_buf = sycl::malloc_shared<char>(size, *stream);
+ SYCL_CHECK(
+ CHECK_TRY_ERROR((*stream).memcpy(tmp_buf, data_device, size)
+ .wait()));
+ GGML_ASSERT((size % sizeof(block_q4_0) == 0));
+ GGML_ASSERT((offset % sizeof(block_q4_0) == 0));
+ int offset_blks = offset / sizeof(block_q4_0);
+ auto qs_ptr = (uint8_t*)data_device + offset_blks * QK4_0 / 2;;
+ auto d_ptr = (sycl::half*)(qs_ptr + ncols * nrows / 2) + offset_blks;
+
+ stream->parallel_for(
+ size / sizeof(block_q4_0),
+ [=](auto i) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
+ const block_q4_0* x = (const block_q4_0*)tmp_buf;
+ const int ib = i;
+
+ for (int j = 0; j < QK4_0/2; j ++)
+ {
+ *(qs_ptr + ib * QK4_0 / 2 + j) = x[ib].qs[j];
+ }
+ *(d_ptr + ib) = x[ib].d;
+ });
+
+ sycl::free(tmp_buf, *stream);
+}
+
+static void reorder_qw(const ggml_tensor * src0, dpct::queue_ptr stream) {
+ char*data_device = (char*)src0->data;
+ size_t ncols = src0->ne[0];
+ size_t nrows = src0->ne[1];
+ size_t size = ggml_nbytes(src0);
+
+ reorder_qw(data_device, ncols, nrows, size, 0, stream);
+}
+
+/*
+* This function could be called when the OP (mul_mat) function support reorder optimizition.
+*/
+static void opt_for_reorder(ggml_backend_sycl_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1,
+ ggml_tensor * dst) {
+ if (!g_ggml_sycl_disable_optimize && //allow optimize, controlled by $GGML_SYCL_DISABLE_OPT
+ ctx->opt_feature.reorder && //allow this device due to good perf, skip the devices with bad perf.
+ dst->op == GGML_OP_MUL_MAT && //limit to some supported cases of Q4_0, to do for more cases.
+ src0->type == GGML_TYPE_Q4_0 &&
+ src1->ne[2]==1 && src1->ne[3]==1) {
+
+ ggml_tensor_extra_gpu* extra = (ggml_tensor_extra_gpu*)src0->extra;
+ if (!extra) return; //only happen in CI/UT permute case.
+
+ if (extra->optimized_feature.reorder) return; //skip the tensor which is handled for reorder.
+
+ reorder_qw(src0, ctx->stream());
+ extra->optimized_feature.reorder = true; //used to decode/dequan in next steps.
+ }
+}
+
static void ggml_sycl_mul_mat(ggml_backend_sycl_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
const bool split = ggml_backend_buffer_is_sycl_split(src0->buffer);
@@ -2925,6 +2983,7 @@ static void ggml_sycl_mul_mat(ggml_backend_sycl_context & ctx, const ggml_tensor
// KQ + KQV multi-batch
ggml_sycl_mul_mat_batched_sycl(ctx, src0, src1, dst);
} else if (use_dequantize_mul_mat_vec) {
+ opt_for_reorder(&ctx, src0, src1, dst); //the OP function in this branch support reorder.
ggml_sycl_op_mul_mat(ctx, src0, src1, dst, ggml_sycl_op_dequantize_mul_mat_vec, false);
// save_tensor_txt("1/dst_1.txt", (float*) dst->data, src0->ne[1], sizeof(float), ctx.stream());
} else if (use_mul_mat_vec_q) {
@@ -2932,6 +2991,7 @@ static void ggml_sycl_mul_mat(ggml_backend_sycl_context & ctx, const ggml_tensor
} else if (use_mul_mat_q) {
ggml_sycl_op_mul_mat(ctx, src0, src1, dst, ggml_sycl_op_mul_mat_q, true);
} else {
+ opt_for_reorder(&ctx, src0, src1, dst); //the OP function in this branch support reorder.
ggml_sycl_op_mul_mat(ctx, src0, src1, dst, ggml_sycl_op_mul_mat_sycl, false);
}
}
@@ -3561,71 +3621,8 @@ catch (sycl::exception const &exc) {
std::exit(1);
}
-static void reorder_qw(char *data_device, const int ncols, const int nrows,
- size_t size, size_t offset, dpct::queue_ptr stream) {
- auto tmp_buf = sycl::malloc_shared<char>(size, *stream);
- SYCL_CHECK(
- CHECK_TRY_ERROR((*stream).memcpy(tmp_buf, data_device, size)
- .wait()));
- GGML_ASSERT((size % sizeof(block_q4_0) == 0));
- GGML_ASSERT((offset % sizeof(block_q4_0) == 0));
- int offset_blks = offset / sizeof(block_q4_0);
- auto qs_ptr = (uint8_t*)data_device + offset_blks * QK4_0 / 2;;
- auto d_ptr = (sycl::half*)(qs_ptr + ncols * nrows / 2) + offset_blks;
-
- stream->parallel_for(
- size / sizeof(block_q4_0),
- [=](auto i) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
- const block_q4_0* x = (const block_q4_0*)tmp_buf;
- const int ib = i;
-
- for (int j = 0; j < QK4_0/2; j ++)
- {
- *(qs_ptr + ib * QK4_0 / 2 + j) = x[ib].qs[j];
- }
- *(d_ptr + ib) = x[ib].d;
- });
-
- sycl::free(tmp_buf, *stream);
-}
-
-static void reorder_qw(ggml_tensor * src0, dpct::queue_ptr stream) {
- char*data_device = (char*)src0->data;
- size_t ncols = src0->ne[0];
- size_t nrows = src0->ne[1];
- size_t size = ggml_nbytes(src0);
-
- reorder_qw(data_device, ncols, nrows, size, 0, stream);
-}
-
-static void opt_for_reorder(ggml_tensor * dst, dpct::queue_ptr stream) {
- ggml_tensor *src0 = dst->src[0];
- ggml_tensor *src1 = dst->src[1];
-
- if (dst->op == GGML_OP_MUL_MAT && src0->type == GGML_TYPE_Q4_0 &&
- src1->ne[2]==1 && src1->ne[3]==1) {
- reorder_qw(src0, stream);
- ggml_tensor_extra_gpu* extra = (ggml_tensor_extra_gpu*)src0->extra;
- GGML_ASSERT(extra);
- extra->optimized_feature.reorder = true; //used to decode/dequan in next steps.
- }
-}
-
-static void optimize_graph_once(ggml_cgraph * cgraph, ggml_backend_sycl_context * ctx) {
- dpct::queue_ptr stream = ctx->stream();
- if (ctx->optimized_graph) {
- return;
- }
- ctx->optimized_graph = true;
-
- for (int i = 0; i < cgraph->n_nodes; i++) {
- if (ctx->opt_feature.reorder) opt_for_reorder(cgraph->nodes[i], stream);
- }
-}
-
static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * sycl_ctx, ggml_cgraph * cgraph) {
ggml_sycl_set_main_device(sycl_ctx->device);
- if (!g_ggml_sycl_disable_optimize) optimize_graph_once(cgraph, sycl_ctx);
for (int i = 0; i < cgraph->n_nodes; i++) {
ggml_tensor * node = cgraph->nodes[i];
| diff --git a/ggml/src/ggml-sycl/common.hpp b/ggml/src/ggml-sycl/common.hpp
index 3e1ceeaa49486..a8187b0a9187f 100644
--- a/ggml/src/ggml-sycl/common.hpp
+++ b/ggml/src/ggml-sycl/common.hpp
@@ -313,7 +313,6 @@ struct ggml_backend_sycl_context {
int device;
std::string name;
optimize_feature opt_feature;
queue_ptr qptrs[GGML_SYCL_MAX_DEVICES][GGML_SYCL_MAX_STREAMS] = { { nullptr } };
diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp
index 4d2fda0bfa6ae..22927338bda42 100644
--- a/ggml/src/ggml-sycl/ggml-sycl.cpp
+++ b/ggml/src/ggml-sycl/ggml-sycl.cpp
@@ -192,7 +192,7 @@ static void ggml_check_sycl() try {
if (!initialized) {
g_ggml_sycl_debug = get_sycl_env("GGML_SYCL_DEBUG", 0);
- g_ggml_sycl_disable_optimize= get_sycl_env("GGML_SYCL_DISABLE_OPT", 1);
+ g_ggml_sycl_disable_optimize= get_sycl_env("GGML_SYCL_DISABLE_OPT", 0);
g_ggml_sycl_disable_graph = get_sycl_env("GGML_SYCL_DISABLE_GRAPH", 1);
GGML_SYCL_DEBUG("[SYCL] call ggml_check_sycl\n");
GGML_LOG_INFO("Running with Environment Variables:\n");
@@ -2863,6 +2863,64 @@ static bool ggml_sycl_supports_dmmv(enum ggml_type type) {
+static void reorder_qw(char *data_device, const int ncols, const int nrows,
+ size_t size, size_t offset, dpct::queue_ptr stream) {
+ auto tmp_buf = sycl::malloc_shared<char>(size, *stream);
+ CHECK_TRY_ERROR((*stream).memcpy(tmp_buf, data_device, size)
+ .wait()));
+ GGML_ASSERT((size % sizeof(block_q4_0) == 0));
+ GGML_ASSERT((offset % sizeof(block_q4_0) == 0));
+ int offset_blks = offset / sizeof(block_q4_0);
+ auto qs_ptr = (uint8_t*)data_device + offset_blks * QK4_0 / 2;;
+ auto d_ptr = (sycl::half*)(qs_ptr + ncols * nrows / 2) + offset_blks;
+ stream->parallel_for(
+ size / sizeof(block_q4_0),
+ [=](auto i) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
+ const block_q4_0* x = (const block_q4_0*)tmp_buf;
+ const int ib = i;
+ for (int j = 0; j < QK4_0/2; j ++)
+ }
+ });
+ sycl::free(tmp_buf, *stream);
+ char*data_device = (char*)src0->data;
+ size_t ncols = src0->ne[0];
+ size_t nrows = src0->ne[1];
+ size_t size = ggml_nbytes(src0);
+ reorder_qw(data_device, ncols, nrows, size, 0, stream);
+* This function could be called when the OP (mul_mat) function support reorder optimizition.
+*/
+static void opt_for_reorder(ggml_backend_sycl_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1,
+ ggml_tensor * dst) {
+ ctx->opt_feature.reorder && //allow this device due to good perf, skip the devices with bad perf.
+ dst->op == GGML_OP_MUL_MAT && //limit to some supported cases of Q4_0, to do for more cases.
+ src0->type == GGML_TYPE_Q4_0 &&
+ src1->ne[2]==1 && src1->ne[3]==1) {
+ ggml_tensor_extra_gpu* extra = (ggml_tensor_extra_gpu*)src0->extra;
+ if (!extra) return; //only happen in CI/UT permute case.
+ if (extra->optimized_feature.reorder) return; //skip the tensor which is handled for reorder.
+ reorder_qw(src0, ctx->stream());
+ extra->optimized_feature.reorder = true; //used to decode/dequan in next steps.
+ }
static void ggml_sycl_mul_mat(ggml_backend_sycl_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
const bool split = ggml_backend_buffer_is_sycl_split(src0->buffer);
@@ -2925,6 +2983,7 @@ static void ggml_sycl_mul_mat(ggml_backend_sycl_context & ctx, const ggml_tensor
// KQ + KQV multi-batch
ggml_sycl_mul_mat_batched_sycl(ctx, src0, src1, dst);
} else if (use_dequantize_mul_mat_vec) {
ggml_sycl_op_mul_mat(ctx, src0, src1, dst, ggml_sycl_op_dequantize_mul_mat_vec, false);
// save_tensor_txt("1/dst_1.txt", (float*) dst->data, src0->ne[1], sizeof(float), ctx.stream());
} else if (use_mul_mat_vec_q) {
@@ -2932,6 +2991,7 @@ static void ggml_sycl_mul_mat(ggml_backend_sycl_context & ctx, const ggml_tensor
} else if (use_mul_mat_q) {
ggml_sycl_op_mul_mat(ctx, src0, src1, dst, ggml_sycl_op_mul_mat_q, true);
} else {
ggml_sycl_op_mul_mat(ctx, src0, src1, dst, ggml_sycl_op_mul_mat_sycl, false);
@@ -3561,71 +3621,8 @@ catch (sycl::exception const &exc) {
std::exit(1);
-static void reorder_qw(char *data_device, const int ncols, const int nrows,
- size_t size, size_t offset, dpct::queue_ptr stream) {
- auto tmp_buf = sycl::malloc_shared<char>(size, *stream);
- SYCL_CHECK(
- CHECK_TRY_ERROR((*stream).memcpy(tmp_buf, data_device, size)
- .wait()));
- GGML_ASSERT((size % sizeof(block_q4_0) == 0));
- GGML_ASSERT((offset % sizeof(block_q4_0) == 0));
- int offset_blks = offset / sizeof(block_q4_0);
- auto qs_ptr = (uint8_t*)data_device + offset_blks * QK4_0 / 2;;
- auto d_ptr = (sycl::half*)(qs_ptr + ncols * nrows / 2) + offset_blks;
- stream->parallel_for(
- size / sizeof(block_q4_0),
- [=](auto i) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
- const block_q4_0* x = (const block_q4_0*)tmp_buf;
- const int ib = i;
- for (int j = 0; j < QK4_0/2; j ++)
- {
- *(qs_ptr + ib * QK4_0 / 2 + j) = x[ib].qs[j];
- }
- *(d_ptr + ib) = x[ib].d;
- });
- sycl::free(tmp_buf, *stream);
-static void reorder_qw(ggml_tensor * src0, dpct::queue_ptr stream) {
- char*data_device = (char*)src0->data;
- size_t ncols = src0->ne[0];
- size_t nrows = src0->ne[1];
- size_t size = ggml_nbytes(src0);
- reorder_qw(data_device, ncols, nrows, size, 0, stream);
-static void opt_for_reorder(ggml_tensor * dst, dpct::queue_ptr stream) {
- ggml_tensor *src0 = dst->src[0];
- ggml_tensor *src1 = dst->src[1];
- src1->ne[2]==1 && src1->ne[3]==1) {
- reorder_qw(src0, stream);
- ggml_tensor_extra_gpu* extra = (ggml_tensor_extra_gpu*)src0->extra;
- GGML_ASSERT(extra);
- extra->optimized_feature.reorder = true; //used to decode/dequan in next steps.
-static void optimize_graph_once(ggml_cgraph * cgraph, ggml_backend_sycl_context * ctx) {
- dpct::queue_ptr stream = ctx->stream();
- if (ctx->optimized_graph) {
- return;
- ctx->optimized_graph = true;
- for (int i = 0; i < cgraph->n_nodes; i++) {
static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * sycl_ctx, ggml_cgraph * cgraph) {
ggml_sycl_set_main_device(sycl_ctx->device);
- if (!g_ggml_sycl_disable_optimize) optimize_graph_once(cgraph, sycl_ctx);
for (int i = 0; i < cgraph->n_nodes; i++) {
ggml_tensor * node = cgraph->nodes[i]; | [
"- bool optimized_graph=false;",
"+ SYCL_CHECK(",
"+ {",
"+ *(qs_ptr + ib * QK4_0 / 2 + j) = x[ib].qs[j];",
"+ *(d_ptr + ib) = x[ib].d;",
"+static void reorder_qw(const ggml_tensor * src0, dpct::queue_ptr stream) {",
"+/*",
"+ if (!g_ggml_sycl_disable_optimize && //allow optimize, controlled by $GGML_SYCL_DISABLE_OPT",
"- if (dst->op == GGML_OP_MUL_MAT && src0->type == GGML_TYPE_Q4_0 &&",
"- if (ctx->opt_feature.reorder) opt_for_reorder(cgraph->nodes[i], stream);"
] | [
8,
32,
48,
49,
51,
57,
66,
71,
151,
168
] | {
"additions": 61,
"author": "NeoZhangJianyu",
"deletions": 65,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/13003",
"issue_id": 13003,
"merged_at": "2025-04-25T09:37:51Z",
"omission_probability": 0.1,
"pr_number": 13003,
"repo": "ggml-org/llama.cpp",
"title": "[SYCL][OPT] Fix reorder optimization for Q4_0",
"total_changes": 126
} |
793 | diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h
index c8b6097f7e573..1e674112767c9 100644
--- a/ggml/include/ggml-rpc.h
+++ b/ggml/include/ggml-rpc.h
@@ -7,7 +7,7 @@
extern "C" {
#endif
-#define RPC_PROTO_MAJOR_VERSION 1
+#define RPC_PROTO_MAJOR_VERSION 2
#define RPC_PROTO_MINOR_VERSION 0
#define RPC_PROTO_PATCH_VERSION 0
#define GGML_RPC_MAX_SERVERS 16
diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp
index a0667b7d702b2..9023eb0919690 100644
--- a/ggml/src/ggml-rpc/ggml-rpc.cpp
+++ b/ggml/src/ggml-rpc/ggml-rpc.cpp
@@ -378,8 +378,8 @@ static bool parse_endpoint(const std::string & endpoint, std::string & host, int
}
// RPC request : | rpc_cmd (1 byte) | request_size (8 bytes) | request_data (request_size bytes) |
-// RPC response: | response_size (8 bytes) | response_data (response_size bytes) |
-static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cmd, const void * input, size_t input_size, void * output, size_t output_size) {
+// No response
+static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cmd, const void * input, size_t input_size) {
uint8_t cmd_byte = cmd;
if (!send_data(sock->fd, &cmd_byte, sizeof(cmd_byte))) {
return false;
@@ -390,6 +390,15 @@ static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cm
if (!send_data(sock->fd, input, input_size)) {
return false;
}
+ return true;
+}
+
+// RPC request : | rpc_cmd (1 byte) | request_size (8 bytes) | request_data (request_size bytes) |
+// RPC response: | response_size (8 bytes) | response_data (response_size bytes) |
+static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cmd, const void * input, size_t input_size, void * output, size_t output_size) {
+ if (!send_rpc_cmd(sock, cmd, input, input_size)) {
+ return false;
+ }
// TODO: currently the output_size is always known, do we need support for commands with variable output size?
// even if we do, we can skip sending output_size from the server for commands with known output size
uint64_t out_size;
@@ -555,7 +564,7 @@ static void ggml_backend_rpc_buffer_set_tensor(ggml_backend_buffer_t buffer, ggm
memcpy(input.data(), &rpc_tensor, sizeof(rpc_tensor));
memcpy(input.data() + sizeof(rpc_tensor), &offset, sizeof(offset));
memcpy(input.data() + sizeof(rpc_tensor) + sizeof(offset), data, size);
- bool status = send_rpc_cmd(ctx->sock, RPC_CMD_SET_TENSOR, input.data(), input.size(), nullptr, 0);
+ bool status = send_rpc_cmd(ctx->sock, RPC_CMD_SET_TENSOR, input.data(), input.size());
GGML_ASSERT(status);
}
@@ -1428,9 +1437,6 @@ static void rpc_serve_client(ggml_backend_t backend, const char * cache_dir,
if (!server.set_tensor(input)) {
return;
}
- if (!send_msg(sockfd, nullptr, 0)) {
- return;
- }
break;
}
case RPC_CMD_SET_TENSOR_HASH: {
| diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h
index c8b6097f7e573..1e674112767c9 100644
--- a/ggml/include/ggml-rpc.h
+++ b/ggml/include/ggml-rpc.h
@@ -7,7 +7,7 @@
extern "C" {
#endif
-#define RPC_PROTO_MAJOR_VERSION 1
+#define RPC_PROTO_MAJOR_VERSION 2
#define RPC_PROTO_MINOR_VERSION 0
#define RPC_PROTO_PATCH_VERSION 0
#define GGML_RPC_MAX_SERVERS 16
diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp
index a0667b7d702b2..9023eb0919690 100644
--- a/ggml/src/ggml-rpc/ggml-rpc.cpp
+++ b/ggml/src/ggml-rpc/ggml-rpc.cpp
@@ -378,8 +378,8 @@ static bool parse_endpoint(const std::string & endpoint, std::string & host, int
// RPC request : | rpc_cmd (1 byte) | request_size (8 bytes) | request_data (request_size bytes) |
-// RPC response: | response_size (8 bytes) | response_data (response_size bytes) |
-static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cmd, const void * input, size_t input_size, void * output, size_t output_size) {
+// No response
+static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cmd, const void * input, size_t input_size) {
uint8_t cmd_byte = cmd;
if (!send_data(sock->fd, &cmd_byte, sizeof(cmd_byte))) {
@@ -390,6 +390,15 @@ static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cm
if (!send_data(sock->fd, input, input_size)) {
}
+ return true;
+}
+// RPC response: | response_size (8 bytes) | response_data (response_size bytes) |
+static bool send_rpc_cmd(const std::shared_ptr<socket_t> & sock, enum rpc_cmd cmd, const void * input, size_t input_size, void * output, size_t output_size) {
+ if (!send_rpc_cmd(sock, cmd, input, input_size)) {
+ return false;
+ }
// TODO: currently the output_size is always known, do we need support for commands with variable output size?
// even if we do, we can skip sending output_size from the server for commands with known output size
uint64_t out_size;
@@ -555,7 +564,7 @@ static void ggml_backend_rpc_buffer_set_tensor(ggml_backend_buffer_t buffer, ggm
memcpy(input.data(), &rpc_tensor, sizeof(rpc_tensor));
memcpy(input.data() + sizeof(rpc_tensor), &offset, sizeof(offset));
memcpy(input.data() + sizeof(rpc_tensor) + sizeof(offset), data, size);
- bool status = send_rpc_cmd(ctx->sock, RPC_CMD_SET_TENSOR, input.data(), input.size(), nullptr, 0);
+ bool status = send_rpc_cmd(ctx->sock, RPC_CMD_SET_TENSOR, input.data(), input.size());
GGML_ASSERT(status);
@@ -1428,9 +1437,6 @@ static void rpc_serve_client(ggml_backend_t backend, const char * cache_dir,
if (!server.set_tensor(input)) {
return;
}
- if (!send_msg(sockfd, nullptr, 0)) {
- return;
- }
break;
}
case RPC_CMD_SET_TENSOR_HASH: { | [
"+",
"+// RPC request : | rpc_cmd (1 byte) | request_size (8 bytes) | request_data (request_size bytes) |"
] | [
34,
35
] | {
"additions": 13,
"author": "rgerganov",
"deletions": 7,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/12943",
"issue_id": 12943,
"merged_at": "2025-04-25T07:08:09Z",
"omission_probability": 0.1,
"pr_number": 12943,
"repo": "ggml-org/llama.cpp",
"title": "rpc : do not wait for response when sending RPC_CMD_SET_TENSOR",
"total_changes": 20
} |
794 | diff --git a/examples/llava/clip-impl.h b/examples/llava/clip-impl.h
index 8d310fb0271c5..53ac381304765 100644
--- a/examples/llava/clip-impl.h
+++ b/examples/llava/clip-impl.h
@@ -90,8 +90,6 @@
#define TN_GLM_ADAPTER_D_H_2_4H "adapter.linear.dense_h_to_4h.%s"
#define TN_GLM_ADAPTER_GATE "adapter.linear.gate.%s"
#define TN_GLM_ADAPTER_D_4H_2_H "adapter.linear.dense_4h_to_h.%s"
-#define TN_GLM_BOI_W "adapter.boi"
-#define TN_GLM_EOI_W "adapter.eoi"
enum projector_type {
PROJECTOR_TYPE_MLP,
diff --git a/examples/llava/clip.cpp b/examples/llava/clip.cpp
index 4eec4a2646798..9a5ab7c819585 100644
--- a/examples/llava/clip.cpp
+++ b/examples/llava/clip.cpp
@@ -244,8 +244,6 @@ struct clip_vision_model {
//GLMV-Edge projection
struct ggml_tensor * mm_model_adapter_conv_w = nullptr;
struct ggml_tensor * mm_model_adapter_conv_b = nullptr;
- struct ggml_tensor * boi_w = nullptr;
- struct ggml_tensor * eoi_w = nullptr;
// MobileVLM projection
struct ggml_tensor * mm_model_mlp_1_w = nullptr;
@@ -1697,8 +1695,6 @@ struct clip_model_loader {
vision_model.mm_model_mlp_1_w = get_tensor(string_format(TN_GLM_ADAPTER_D_H_2_4H,"weight"));
vision_model.mm_model_mlp_2_w = get_tensor(string_format(TN_GLM_ADAPTER_GATE,"weight"));
vision_model.mm_model_mlp_3_w = get_tensor(string_format(TN_GLM_ADAPTER_D_4H_2_H,"weight"));
- vision_model.boi_w = get_tensor(TN_GLM_BOI_W);
- vision_model.eoi_w = get_tensor(TN_GLM_EOI_W);
} break;
case PROJECTOR_TYPE_MERGER:
{
@@ -2593,8 +2589,7 @@ void clip_free(clip_ctx * ctx) {
}
size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
- int extra_tokens = ctx->has_glm_projector ? 2 : 0;
- return (clip_n_patches(ctx) + extra_tokens) * clip_n_mmproj_embd(ctx) * sizeof(float);
+ return clip_n_patches(ctx) * clip_n_mmproj_embd(ctx) * sizeof(float);
}
size_t clip_embd_nbytes_by_img(const struct clip_ctx * ctx, int img_h, int img_w) {
@@ -2790,9 +2785,6 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
}
if (ctx->has_glm_projector) {
GGML_ASSERT(batch_size == 1);
- ggml_tensor * boi = ctx->vision_model.boi_w;
- ggml_backend_tensor_get(boi,vec,0,ggml_nbytes(boi));
- vec = (float*)(vec+ggml_nelements(boi)); //offset for boi
}
// build the inference graph
@@ -3001,13 +2993,6 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
// copy the embeddings to the location passed by the user
ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
- if (ctx->has_glm_projector) {
- //eoi
- ggml_tensor * eoi = ctx->vision_model.eoi_w;
- int offset = ggml_nelements(embeddings);
- ggml_backend_tensor_get(eoi, vec+offset, 0, ggml_nbytes(eoi));
- }
-
return true;
}
diff --git a/examples/llava/mtmd.cpp b/examples/llava/mtmd.cpp
index 11ca7b30f1ac6..a994ef0166e6a 100644
--- a/examples/llava/mtmd.cpp
+++ b/examples/llava/mtmd.cpp
@@ -186,6 +186,11 @@ int32_t mtmd_tokenize(mtmd_context * ctx,
marker_modified = "<start_of_image>" + ctx->image_marker + "<end_of_image>";
string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
+ } else if (proj_type == PROJECTOR_TYPE_GLM_EDGE) {
+ // <|begin_of_image|> ... (image embeddings) ... <|end_of_image|>
+ marker_modified = "<|begin_of_image|>" + ctx->image_marker + "<|end_of_image|>";
+ string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
+
} else if (proj_type == PROJECTOR_TYPE_IDEFICS3) {
// https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
marker_modified = "<fake_token_around_image><global-img>" + ctx->image_marker + "<fake_token_around_image>";
| diff --git a/examples/llava/clip-impl.h b/examples/llava/clip-impl.h
index 8d310fb0271c5..53ac381304765 100644
--- a/examples/llava/clip-impl.h
+++ b/examples/llava/clip-impl.h
@@ -90,8 +90,6 @@
#define TN_GLM_ADAPTER_D_H_2_4H "adapter.linear.dense_h_to_4h.%s"
#define TN_GLM_ADAPTER_GATE "adapter.linear.gate.%s"
#define TN_GLM_ADAPTER_D_4H_2_H "adapter.linear.dense_4h_to_h.%s"
-#define TN_GLM_BOI_W "adapter.boi"
-#define TN_GLM_EOI_W "adapter.eoi"
enum projector_type {
PROJECTOR_TYPE_MLP,
diff --git a/examples/llava/clip.cpp b/examples/llava/clip.cpp
index 4eec4a2646798..9a5ab7c819585 100644
--- a/examples/llava/clip.cpp
+++ b/examples/llava/clip.cpp
@@ -244,8 +244,6 @@ struct clip_vision_model {
//GLMV-Edge projection
struct ggml_tensor * mm_model_adapter_conv_w = nullptr;
struct ggml_tensor * mm_model_adapter_conv_b = nullptr;
- struct ggml_tensor * boi_w = nullptr;
- struct ggml_tensor * eoi_w = nullptr;
// MobileVLM projection
struct ggml_tensor * mm_model_mlp_1_w = nullptr;
@@ -1697,8 +1695,6 @@ struct clip_model_loader {
vision_model.mm_model_mlp_1_w = get_tensor(string_format(TN_GLM_ADAPTER_D_H_2_4H,"weight"));
vision_model.mm_model_mlp_2_w = get_tensor(string_format(TN_GLM_ADAPTER_GATE,"weight"));
vision_model.mm_model_mlp_3_w = get_tensor(string_format(TN_GLM_ADAPTER_D_4H_2_H,"weight"));
- vision_model.boi_w = get_tensor(TN_GLM_BOI_W);
- vision_model.eoi_w = get_tensor(TN_GLM_EOI_W);
} break;
case PROJECTOR_TYPE_MERGER:
{
@@ -2593,8 +2589,7 @@ void clip_free(clip_ctx * ctx) {
size_t clip_embd_nbytes(const struct clip_ctx * ctx) {
- int extra_tokens = ctx->has_glm_projector ? 2 : 0;
- return (clip_n_patches(ctx) + extra_tokens) * clip_n_mmproj_embd(ctx) * sizeof(float);
size_t clip_embd_nbytes_by_img(const struct clip_ctx * ctx, int img_h, int img_w) {
@@ -2790,9 +2785,6 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
if (ctx->has_glm_projector) {
GGML_ASSERT(batch_size == 1);
- ggml_tensor * boi = ctx->vision_model.boi_w;
- ggml_backend_tensor_get(boi,vec,0,ggml_nbytes(boi));
- vec = (float*)(vec+ggml_nelements(boi)); //offset for boi
// build the inference graph
@@ -3001,13 +2993,6 @@ bool clip_image_batch_encode(clip_ctx * ctx, const int n_threads, const clip_ima
// copy the embeddings to the location passed by the user
ggml_backend_tensor_get(embeddings, vec, 0, ggml_nbytes(embeddings));
- if (ctx->has_glm_projector) {
- //eoi
- ggml_tensor * eoi = ctx->vision_model.eoi_w;
- int offset = ggml_nelements(embeddings);
- ggml_backend_tensor_get(eoi, vec+offset, 0, ggml_nbytes(eoi));
- }
-
return true;
diff --git a/examples/llava/mtmd.cpp b/examples/llava/mtmd.cpp
index 11ca7b30f1ac6..a994ef0166e6a 100644
--- a/examples/llava/mtmd.cpp
+++ b/examples/llava/mtmd.cpp
@@ -186,6 +186,11 @@ int32_t mtmd_tokenize(mtmd_context * ctx,
marker_modified = "<start_of_image>" + ctx->image_marker + "<end_of_image>";
string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
+ } else if (proj_type == PROJECTOR_TYPE_GLM_EDGE) {
+ // <|begin_of_image|> ... (image embeddings) ... <|end_of_image|>
+ marker_modified = "<|begin_of_image|>" + ctx->image_marker + "<|end_of_image|>";
+ string_replace_all(prompt_modified, ctx->image_marker, marker_modified);
+
} else if (proj_type == PROJECTOR_TYPE_IDEFICS3) {
// https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
marker_modified = "<fake_token_around_image><global-img>" + ctx->image_marker + "<fake_token_around_image>"; | [
"+ return clip_n_patches(ctx) * clip_n_mmproj_embd(ctx) * sizeof(float);"
] | [
41
] | {
"additions": 6,
"author": "ngxson",
"deletions": 18,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/13081",
"issue_id": 13081,
"merged_at": "2025-04-24T20:17:05Z",
"omission_probability": 0.1,
"pr_number": 13081,
"repo": "ggml-org/llama.cpp",
"title": "clip : remove boi/eoi embeddings for GLM-edge model (⚠️ breaking change)",
"total_changes": 24
} |
795 | diff --git a/common/arg.cpp b/common/arg.cpp
index 47c26955ea374..fa22e86cd14e6 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -1,6 +1,7 @@
#include "gguf.h" // for reading GGUF splits
#include "arg.h"
+#include "common.h"
#include "log.h"
#include "sampling.h"
#include "chat.h"
@@ -848,6 +849,10 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context
params.kv_overrides.back().key[0] = 0;
}
+ if (!params.tensor_buft_overrides.empty()) {
+ params.tensor_buft_overrides.push_back({nullptr, nullptr});
+ }
+
if (params.reranking && params.embedding) {
throw std::invalid_argument("error: either --embedding or --reranking can be specified, but not both");
}
@@ -2180,6 +2185,41 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
exit(0);
}
));
+ add_opt(common_arg(
+ {"--override-tensor", "-ot"}, "<tensor name pattern>=<buffer type>,...",
+ "override tensor buffer type", [](common_params & params, const std::string & value) {
+ /* static */ std::map<std::string, ggml_backend_buffer_type_t> buft_list;
+ if (buft_list.empty()) {
+ // enumerate all the devices and add their buffer types to the list
+ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
+ auto * dev = ggml_backend_dev_get(i);
+ auto * buft = ggml_backend_dev_buffer_type(dev);
+ if (buft) {
+ buft_list[ggml_backend_buft_name(buft)] = buft;
+ }
+ }
+ }
+
+ for (const auto & override : string_split<std::string>(value, ',')) {
+ std::string::size_type pos = override.find('=');
+ if (pos == std::string::npos) {
+ throw std::invalid_argument("invalid value");
+ }
+ std::string tensor_name = override.substr(0, pos);
+ std::string buffer_type = override.substr(pos + 1);
+
+ if (buft_list.find(buffer_type) == buft_list.end()) {
+ printf("Available buffer types:\n");
+ for (const auto & it : buft_list) {
+ printf(" %s\n", ggml_backend_buft_name(it.second));
+ }
+ throw std::invalid_argument("unknown buffer type");
+ }
+ // FIXME: this leaks memory
+ params.tensor_buft_overrides.push_back({strdup(tensor_name.c_str()), buft_list.at(buffer_type)});
+ }
+ }
+ ));
add_opt(common_arg(
{"-ngl", "--gpu-layers", "--n-gpu-layers"}, "N",
"number of layers to store in VRAM",
diff --git a/common/common.cpp b/common/common.cpp
index 22642c84afa40..a21630e091d78 100644
--- a/common/common.cpp
+++ b/common/common.cpp
@@ -1047,15 +1047,18 @@ struct llama_model_params common_model_params_to_llama(common_params & params) {
if (!params.devices.empty()) {
mparams.devices = params.devices.data();
}
+
if (params.n_gpu_layers != -1) {
mparams.n_gpu_layers = params.n_gpu_layers;
}
+
mparams.main_gpu = params.main_gpu;
mparams.split_mode = params.split_mode;
mparams.tensor_split = params.tensor_split;
mparams.use_mmap = params.use_mmap;
mparams.use_mlock = params.use_mlock;
mparams.check_tensors = params.check_tensors;
+
if (params.kv_overrides.empty()) {
mparams.kv_overrides = NULL;
} else {
@@ -1063,6 +1066,13 @@ struct llama_model_params common_model_params_to_llama(common_params & params) {
mparams.kv_overrides = params.kv_overrides.data();
}
+ if (params.tensor_buft_overrides.empty()) {
+ mparams.tensor_buft_overrides = NULL;
+ } else {
+ GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
+ mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
+ }
+
return mparams;
}
diff --git a/common/common.h b/common/common.h
index 41ff9905e4416..15f4b2dff5b15 100644
--- a/common/common.h
+++ b/common/common.h
@@ -283,6 +283,7 @@ struct common_params {
std::vector<std::string> in_files; // all input files
std::vector<std::string> antiprompt; // strings upon which more user input is prompted (a.k.a. reverse prompts)
std::vector<llama_model_kv_override> kv_overrides;
+ std::vector<llama_model_tensor_buft_override> tensor_buft_overrides;
bool lora_init_without_apply = false; // only load lora to memory, but do not apply it to ctx (user can manually apply lora later using llama_adapter_lora_apply)
std::vector<common_adapter_lora_info> lora_adapters; // lora adapter path with user defined scale
diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c
index 161dd3fa94547..3e274d6ae3961 100644
--- a/ggml/src/ggml.c
+++ b/ggml/src/ggml.c
@@ -1159,6 +1159,12 @@ int64_t ggml_nrows(const struct ggml_tensor * tensor) {
}
size_t ggml_nbytes(const struct ggml_tensor * tensor) {
+ for (int i = 0; i < GGML_MAX_DIMS; ++i) {
+ if (tensor->ne[i] <= 0) {
+ return 0;
+ }
+ }
+
size_t nbytes;
const size_t blck_size = ggml_blck_size(tensor->type);
if (blck_size == 1) {
diff --git a/include/llama.h b/include/llama.h
index 468ab1fa485da..fca2b034ba270 100644
--- a/include/llama.h
+++ b/include/llama.h
@@ -280,10 +280,18 @@ extern "C" {
};
};
+ struct llama_model_tensor_buft_override {
+ const char * pattern;
+ ggml_backend_buffer_type_t buft;
+ };
+
struct llama_model_params {
// NULL-terminated list of devices to use for offloading (if NULL, all available devices are used)
ggml_backend_dev_t * devices;
+ // NULL-terminated list of buffer types to use for tensors that match a pattern
+ const struct llama_model_tensor_buft_override * tensor_buft_overrides;
+
int32_t n_gpu_layers; // number of layers to store in VRAM
enum llama_split_mode split_mode; // how to split the model across multiple GPUs
diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 3479a8cca3d64..70efb22f7b5e3 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -255,7 +255,8 @@ llama_context::llama_context(
model.n_devices() > 1 &&
model.params.n_gpu_layers > (int) model.hparams.n_layer &&
model.params.split_mode == LLAMA_SPLIT_MODE_LAYER &&
- cparams.offload_kqv;
+ cparams.offload_kqv &&
+ !model.has_tensor_overrides();
// pipeline parallelism requires support for async compute and events in all devices
if (pipeline_parallel) {
diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp
index 1be0f2d6d6c20..ec1d78e3144eb 100644
--- a/src/llama-model-loader.cpp
+++ b/src/llama-model-loader.cpp
@@ -445,7 +445,8 @@ llama_model_loader::llama_model_loader(
std::vector<std::string> & splits,
bool use_mmap,
bool check_tensors,
- const struct llama_model_kv_override * param_overrides_p) {
+ const llama_model_kv_override * param_overrides_p,
+ const llama_model_tensor_buft_override * param_tensor_buft_overrides_p) {
int trace = 0;
if (getenv("LLAMA_TRACE")) {
trace = atoi(getenv("LLAMA_TRACE"));
@@ -457,6 +458,8 @@ llama_model_loader::llama_model_loader(
}
}
+ tensor_buft_overrides = param_tensor_buft_overrides_p;
+
// Load the main GGUF
struct ggml_context * ctx = NULL;
struct gguf_init_params params = {
diff --git a/src/llama-model-loader.h b/src/llama-model-loader.h
index fe35404b26889..0f52b011b6986 100644
--- a/src/llama-model-loader.h
+++ b/src/llama-model-loader.h
@@ -77,8 +77,9 @@ struct llama_model_loader {
llama_mmaps mappings;
- std::map<std::string, struct llama_tensor_weight, weight_name_comparer> weights_map;
- std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
+ std::map<std::string, llama_tensor_weight, weight_name_comparer> weights_map;
+ std::unordered_map<std::string, llama_model_kv_override> kv_overrides;
+ const llama_model_tensor_buft_override * tensor_buft_overrides;
gguf_context_ptr meta;
std::vector<ggml_context_ptr> contexts;
@@ -95,7 +96,8 @@ struct llama_model_loader {
std::vector<std::string> & splits, // optional, only need if the split does not follow naming scheme
bool use_mmap,
bool check_tensors,
- const struct llama_model_kv_override * param_overrides_p);
+ const llama_model_kv_override * param_overrides_p,
+ const llama_model_tensor_buft_override * param_tensor_buft_overrides_p);
template<typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index 8d525e1bec4e0..ca6e3ab2caeb1 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -17,6 +17,7 @@
#include <cmath>
#include <functional>
#include <map>
+#include <regex>
#include <sstream>
#include <stdexcept>
@@ -378,9 +379,12 @@ struct llama_model::impl {
layer_dev dev_input = {};
layer_dev dev_output = {};
std::vector<layer_dev> dev_layer;
+
+ bool has_tensor_overrides;
};
llama_model::llama_model(const llama_model_params & params) : params(params), pimpl(std::make_unique<impl>()) {
+ pimpl->has_tensor_overrides = params.tensor_buft_overrides && params.tensor_buft_overrides[0].pattern;
}
llama_model::~llama_model() {}
@@ -1571,9 +1575,26 @@ bool llama_model::load_tensors(llama_model_loader & ml) {
GGML_ABORT("invalid layer %d for tensor %s", info.layer, tn.str().c_str());
}
- ggml_backend_buffer_type_t buft = select_weight_buft(hparams, t_meta, op, *buft_list);
+ ggml_backend_buffer_type_t buft = nullptr;
+
+ // check overrides
+ if (ml.tensor_buft_overrides) {
+ std::string tensor_name = tn.str();
+ for (const auto * overrides = ml.tensor_buft_overrides; overrides->pattern != nullptr; ++overrides) {
+ std::regex pattern(overrides->pattern);
+ if (std::regex_search(tensor_name, pattern)) {
+ LLAMA_LOG_DEBUG("tensor %s buffer type overriden to %s\n", tensor_name.c_str(), ggml_backend_buft_name(overrides->buft));
+ buft = overrides->buft;
+ break;
+ }
+ }
+ }
+
if (!buft) {
- throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", tn.str().c_str()));
+ buft = select_weight_buft(hparams, t_meta, op, *buft_list);
+ if (!buft) {
+ throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", tn.str().c_str()));
+ }
}
// avoid using a host buffer when using mmap
@@ -4151,6 +4172,10 @@ ggml_backend_buffer_type_t llama_model::select_buft(int il) const {
});
}
+bool llama_model::has_tensor_overrides() const {
+ return pimpl->has_tensor_overrides;
+}
+
const ggml_tensor * llama_model::get_tensor(const char * name) const {
auto it = std::find_if(tensors_by_name.begin(), tensors_by_name.end(),
[name](const std::pair<std::string, ggml_tensor *> & it) {
@@ -12319,6 +12344,7 @@ llm_graph_result_ptr llama_model::build_graph(
llama_model_params llama_model_default_params() {
llama_model_params result = {
/*.devices =*/ nullptr,
+ /*.tensor_buft_overrides =*/ nullptr,
/*.n_gpu_layers =*/ 0,
/*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
/*.main_gpu =*/ 0,
diff --git a/src/llama-model.h b/src/llama-model.h
index f1bf0df3a4ef6..91e6e8725acd2 100644
--- a/src/llama-model.h
+++ b/src/llama-model.h
@@ -382,6 +382,8 @@ struct llama_model {
ggml_backend_buffer_type_t select_buft(int il) const;
+ bool has_tensor_overrides() const;
+
const struct ggml_tensor * get_tensor(const char * name) const;
// TODO: move this to new llm_arch_model_i interface
diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp
index 09eb570779ce5..e3e10fa6cf77f 100644
--- a/src/llama-quant.cpp
+++ b/src/llama-quant.cpp
@@ -527,7 +527,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
}
std::vector<std::string> splits = {};
- llama_model_loader ml(fname_inp, splits, use_mmap, /*check_tensors*/ true, kv_overrides);
+ llama_model_loader ml(fname_inp, splits, use_mmap, /*check_tensors*/ true, kv_overrides, nullptr);
ml.init_mappings(false); // no prefetching
llama_model model(llama_model_default_params());
diff --git a/src/llama.cpp b/src/llama.cpp
index 81e1dd1d0873a..d5164720b2196 100644
--- a/src/llama.cpp
+++ b/src/llama.cpp
@@ -92,7 +92,7 @@ static int llama_model_load(const std::string & fname, std::vector<std::string>
model.t_start_us = tm.t_start_us;
try {
- llama_model_loader ml(fname, splits, params.use_mmap, params.check_tensors, params.kv_overrides);
+ llama_model_loader ml(fname, splits, params.use_mmap, params.check_tensors, params.kv_overrides, params.tensor_buft_overrides);
ml.print_info();
| diff --git a/common/arg.cpp b/common/arg.cpp
index 47c26955ea374..fa22e86cd14e6 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -1,6 +1,7 @@
#include "gguf.h" // for reading GGUF splits
#include "arg.h"
+#include "common.h"
#include "log.h"
#include "sampling.h"
#include "chat.h"
@@ -848,6 +849,10 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context
params.kv_overrides.back().key[0] = 0;
+ params.tensor_buft_overrides.push_back({nullptr, nullptr});
if (params.reranking && params.embedding) {
throw std::invalid_argument("error: either --embedding or --reranking can be specified, but not both");
@@ -2180,6 +2185,41 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
exit(0);
));
+ add_opt(common_arg(
+ {"--override-tensor", "-ot"}, "<tensor name pattern>=<buffer type>,...",
+ "override tensor buffer type", [](common_params & params, const std::string & value) {
+ /* static */ std::map<std::string, ggml_backend_buffer_type_t> buft_list;
+ if (buft_list.empty()) {
+ // enumerate all the devices and add their buffer types to the list
+ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
+ auto * dev = ggml_backend_dev_get(i);
+ auto * buft = ggml_backend_dev_buffer_type(dev);
+ if (buft) {
+ buft_list[ggml_backend_buft_name(buft)] = buft;
+ for (const auto & override : string_split<std::string>(value, ',')) {
+ std::string::size_type pos = override.find('=');
+ if (pos == std::string::npos) {
+ throw std::invalid_argument("invalid value");
+ std::string buffer_type = override.substr(pos + 1);
+ if (buft_list.find(buffer_type) == buft_list.end()) {
+ for (const auto & it : buft_list) {
+ printf(" %s\n", ggml_backend_buft_name(it.second));
+ throw std::invalid_argument("unknown buffer type");
+ // FIXME: this leaks memory
+ params.tensor_buft_overrides.push_back({strdup(tensor_name.c_str()), buft_list.at(buffer_type)});
+ ));
add_opt(common_arg(
{"-ngl", "--gpu-layers", "--n-gpu-layers"}, "N",
"number of layers to store in VRAM",
diff --git a/common/common.cpp b/common/common.cpp
index 22642c84afa40..a21630e091d78 100644
--- a/common/common.cpp
+++ b/common/common.cpp
@@ -1047,15 +1047,18 @@ struct llama_model_params common_model_params_to_llama(common_params & params) {
if (!params.devices.empty()) {
mparams.devices = params.devices.data();
if (params.n_gpu_layers != -1) {
mparams.n_gpu_layers = params.n_gpu_layers;
mparams.main_gpu = params.main_gpu;
mparams.split_mode = params.split_mode;
mparams.tensor_split = params.tensor_split;
mparams.use_mmap = params.use_mmap;
mparams.use_mlock = params.use_mlock;
mparams.check_tensors = params.check_tensors;
if (params.kv_overrides.empty()) {
mparams.kv_overrides = NULL;
} else {
@@ -1063,6 +1066,13 @@ struct llama_model_params common_model_params_to_llama(common_params & params) {
mparams.kv_overrides = params.kv_overrides.data();
+ if (params.tensor_buft_overrides.empty()) {
+ mparams.tensor_buft_overrides = NULL;
+ } else {
+ GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
+ mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
return mparams;
diff --git a/common/common.h b/common/common.h
index 41ff9905e4416..15f4b2dff5b15 100644
--- a/common/common.h
+++ b/common/common.h
@@ -283,6 +283,7 @@ struct common_params {
std::vector<std::string> in_files; // all input files
std::vector<std::string> antiprompt; // strings upon which more user input is prompted (a.k.a. reverse prompts)
std::vector<llama_model_kv_override> kv_overrides;
+ std::vector<llama_model_tensor_buft_override> tensor_buft_overrides;
bool lora_init_without_apply = false; // only load lora to memory, but do not apply it to ctx (user can manually apply lora later using llama_adapter_lora_apply)
std::vector<common_adapter_lora_info> lora_adapters; // lora adapter path with user defined scale
diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c
index 161dd3fa94547..3e274d6ae3961 100644
--- a/ggml/src/ggml.c
+++ b/ggml/src/ggml.c
@@ -1159,6 +1159,12 @@ int64_t ggml_nrows(const struct ggml_tensor * tensor) {
size_t ggml_nbytes(const struct ggml_tensor * tensor) {
+ for (int i = 0; i < GGML_MAX_DIMS; ++i) {
+ if (tensor->ne[i] <= 0) {
+ return 0;
size_t nbytes;
const size_t blck_size = ggml_blck_size(tensor->type);
if (blck_size == 1) {
diff --git a/include/llama.h b/include/llama.h
index 468ab1fa485da..fca2b034ba270 100644
--- a/include/llama.h
+++ b/include/llama.h
@@ -280,10 +280,18 @@ extern "C" {
};
};
+ struct llama_model_tensor_buft_override {
+ const char * pattern;
+ ggml_backend_buffer_type_t buft;
+ };
struct llama_model_params {
// NULL-terminated list of devices to use for offloading (if NULL, all available devices are used)
ggml_backend_dev_t * devices;
+ // NULL-terminated list of buffer types to use for tensors that match a pattern
+ const struct llama_model_tensor_buft_override * tensor_buft_overrides;
int32_t n_gpu_layers; // number of layers to store in VRAM
enum llama_split_mode split_mode; // how to split the model across multiple GPUs
diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 3479a8cca3d64..70efb22f7b5e3 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -255,7 +255,8 @@ llama_context::llama_context(
model.n_devices() > 1 &&
model.params.n_gpu_layers > (int) model.hparams.n_layer &&
model.params.split_mode == LLAMA_SPLIT_MODE_LAYER &&
+ cparams.offload_kqv &&
+ !model.has_tensor_overrides();
// pipeline parallelism requires support for async compute and events in all devices
if (pipeline_parallel) {
diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp
index 1be0f2d6d6c20..ec1d78e3144eb 100644
--- a/src/llama-model-loader.cpp
+++ b/src/llama-model-loader.cpp
@@ -445,7 +445,8 @@ llama_model_loader::llama_model_loader(
std::vector<std::string> & splits,
- const struct llama_model_kv_override * param_overrides_p) {
+ const llama_model_tensor_buft_override * param_tensor_buft_overrides_p) {
int trace = 0;
if (getenv("LLAMA_TRACE")) {
trace = atoi(getenv("LLAMA_TRACE"));
@@ -457,6 +458,8 @@ llama_model_loader::llama_model_loader(
+ tensor_buft_overrides = param_tensor_buft_overrides_p;
// Load the main GGUF
struct ggml_context * ctx = NULL;
struct gguf_init_params params = {
diff --git a/src/llama-model-loader.h b/src/llama-model-loader.h
index fe35404b26889..0f52b011b6986 100644
--- a/src/llama-model-loader.h
+++ b/src/llama-model-loader.h
@@ -77,8 +77,9 @@ struct llama_model_loader {
llama_mmaps mappings;
- std::map<std::string, struct llama_tensor_weight, weight_name_comparer> weights_map;
- std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
+ std::map<std::string, llama_tensor_weight, weight_name_comparer> weights_map;
+ std::unordered_map<std::string, llama_model_kv_override> kv_overrides;
+ const llama_model_tensor_buft_override * tensor_buft_overrides;
gguf_context_ptr meta;
std::vector<ggml_context_ptr> contexts;
@@ -95,7 +96,8 @@ struct llama_model_loader {
std::vector<std::string> & splits, // optional, only need if the split does not follow naming scheme
- const struct llama_model_kv_override * param_overrides_p);
+ const llama_model_tensor_buft_override * param_tensor_buft_overrides_p);
template<typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index 8d525e1bec4e0..ca6e3ab2caeb1 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -17,6 +17,7 @@
#include <cmath>
#include <functional>
#include <map>
+#include <regex>
#include <sstream>
#include <stdexcept>
@@ -378,9 +379,12 @@ struct llama_model::impl {
layer_dev dev_input = {};
layer_dev dev_output = {};
std::vector<layer_dev> dev_layer;
+ bool has_tensor_overrides;
};
llama_model::llama_model(const llama_model_params & params) : params(params), pimpl(std::make_unique<impl>()) {
+ pimpl->has_tensor_overrides = params.tensor_buft_overrides && params.tensor_buft_overrides[0].pattern;
llama_model::~llama_model() {}
@@ -1571,9 +1575,26 @@ bool llama_model::load_tensors(llama_model_loader & ml) {
GGML_ABORT("invalid layer %d for tensor %s", info.layer, tn.str().c_str());
- ggml_backend_buffer_type_t buft = select_weight_buft(hparams, t_meta, op, *buft_list);
+ ggml_backend_buffer_type_t buft = nullptr;
+ // check overrides
+ if (ml.tensor_buft_overrides) {
+ std::string tensor_name = tn.str();
+ for (const auto * overrides = ml.tensor_buft_overrides; overrides->pattern != nullptr; ++overrides) {
+ std::regex pattern(overrides->pattern);
+ LLAMA_LOG_DEBUG("tensor %s buffer type overriden to %s\n", tensor_name.c_str(), ggml_backend_buft_name(overrides->buft));
+ break;
if (!buft) {
- throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", tn.str().c_str()));
+ buft = select_weight_buft(hparams, t_meta, op, *buft_list);
+ if (!buft) {
+ throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", tn.str().c_str()));
// avoid using a host buffer when using mmap
@@ -4151,6 +4172,10 @@ ggml_backend_buffer_type_t llama_model::select_buft(int il) const {
});
+bool llama_model::has_tensor_overrides() const {
+ return pimpl->has_tensor_overrides;
+}
const ggml_tensor * llama_model::get_tensor(const char * name) const {
auto it = std::find_if(tensors_by_name.begin(), tensors_by_name.end(),
[name](const std::pair<std::string, ggml_tensor *> & it) {
@@ -12319,6 +12344,7 @@ llm_graph_result_ptr llama_model::build_graph(
llama_model_params llama_model_default_params() {
llama_model_params result = {
/*.devices =*/ nullptr,
+ /*.tensor_buft_overrides =*/ nullptr,
/*.n_gpu_layers =*/ 0,
/*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
/*.main_gpu =*/ 0,
diff --git a/src/llama-model.h b/src/llama-model.h
index f1bf0df3a4ef6..91e6e8725acd2 100644
--- a/src/llama-model.h
+++ b/src/llama-model.h
@@ -382,6 +382,8 @@ struct llama_model {
ggml_backend_buffer_type_t select_buft(int il) const;
+ bool has_tensor_overrides() const;
const struct ggml_tensor * get_tensor(const char * name) const;
// TODO: move this to new llm_arch_model_i interface
diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp
index 09eb570779ce5..e3e10fa6cf77f 100644
--- a/src/llama-quant.cpp
+++ b/src/llama-quant.cpp
@@ -527,7 +527,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
std::vector<std::string> splits = {};
- llama_model_loader ml(fname_inp, splits, use_mmap, /*check_tensors*/ true, kv_overrides);
ml.init_mappings(false); // no prefetching
llama_model model(llama_model_default_params());
diff --git a/src/llama.cpp b/src/llama.cpp
index 81e1dd1d0873a..d5164720b2196 100644
--- a/src/llama.cpp
+++ b/src/llama.cpp
@@ -92,7 +92,7 @@ static int llama_model_load(const std::string & fname, std::vector<std::string>
model.t_start_us = tm.t_start_us;
try {
- llama_model_loader ml(fname, splits, params.use_mmap, params.check_tensors, params.kv_overrides);
+ llama_model_loader ml(fname, splits, params.use_mmap, params.check_tensors, params.kv_overrides, params.tensor_buft_overrides);
ml.print_info(); | [
"+ if (!params.tensor_buft_overrides.empty()) {",
"+ std::string tensor_name = override.substr(0, pos);",
"+ printf(\"Available buffer types:\\n\");",
"- cparams.offload_kqv;",
"+ if (std::regex_search(tensor_name, pattern)) {",
"+ buft = overrides->buft;",
"+ llama_model_loader ml(fname_inp, splits, use_mmap, /*check_tensors*/ true, kv_overrides, nullptr);"
] | [
16,
47,
51,
162,
254,
256,
312
] | {
"additions": 108,
"author": "slaren",
"deletions": 9,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/11397",
"issue_id": 11397,
"merged_at": "2025-04-02T12:52:01Z",
"omission_probability": 0.1,
"pr_number": 11397,
"repo": "ggml-org/llama.cpp",
"title": "llama : add option to override model tensor buffers",
"total_changes": 117
} |
796 | diff --git a/examples/server/public/index.html.gz b/examples/server/public/index.html.gz
index 941815c22efb0..674e227571e2d 100644
Binary files a/examples/server/public/index.html.gz and b/examples/server/public/index.html.gz differ
diff --git a/examples/server/webui/src/components/ChatScreen.tsx b/examples/server/webui/src/components/ChatScreen.tsx
index d12b06e125e5a..29ab5ea64f76f 100644
--- a/examples/server/webui/src/components/ChatScreen.tsx
+++ b/examples/server/webui/src/components/ChatScreen.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { CallbackGeneratedChunk, useAppContext } from '../utils/app.context';
import ChatMessage from './ChatMessage';
import { CanvasType, Message, PendingMessage } from '../utils/types';
@@ -6,6 +6,7 @@ import { classNames, cleanCurrentUrl, throttle } from '../utils/misc';
import CanvasPyInterpreter from './CanvasPyInterpreter';
import StorageUtils from '../utils/storage';
import { useVSCodeContext } from '../utils/llama-vscode';
+import { useChatTextarea, ChatTextareaApi } from './useChatTextarea.ts';
/**
* A message display is a message node with additional information for rendering.
@@ -99,7 +100,8 @@ export default function ChatScreen() {
canvasData,
replaceMessageAndGenerate,
} = useAppContext();
- const textarea = useOptimizedTextarea(prefilledMsg.content());
+
+ const textarea: ChatTextareaApi = useChatTextarea(prefilledMsg.content());
const { extraContext, clearExtraContext } = useVSCodeContext(textarea);
// TODO: improve this when we have "upload file" feature
@@ -248,14 +250,16 @@ export default function ChatScreen() {
</div>
{/* chat input */}
- <div className="flex flex-row items-center pt-8 pb-6 sticky bottom-0 bg-base-100">
+ <div className="flex flex-row items-end pt-8 pb-6 sticky bottom-0 bg-base-100">
<textarea
- className="textarea textarea-bordered w-full"
+ // Default (mobile): Enable vertical resize, overflow auto for scrolling if needed
+ // Large screens (lg:): Disable manual resize, apply max-height for autosize limit
+ className="textarea textarea-bordered w-full resize-vertical lg:resize-none lg:max-h-48 lg:overflow-y-auto" // Adjust lg:max-h-48 as needed (e.g., lg:max-h-60)
placeholder="Type a message (Shift+Enter to add a new line)"
ref={textarea.ref}
+ onInput={textarea.onInput} // Hook's input handler (will only resize height on lg+ screens)
onKeyDown={(e) => {
if (e.nativeEvent.isComposing || e.keyCode === 229) return;
- if (e.key === 'Enter' && e.shiftKey) return;
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendNewMessage();
@@ -263,7 +267,11 @@ export default function ChatScreen() {
}}
id="msg-input"
dir="auto"
+ // Set a base height of 2 rows for mobile views
+ // On lg+ screens, the hook will calculate and set the initial height anyway
+ rows={2}
></textarea>
+
{isGenerating(currConvId ?? '') ? (
<button
className="btn btn-neutral ml-2"
@@ -286,43 +294,3 @@ export default function ChatScreen() {
</div>
);
}
-
-export interface OptimizedTextareaValue {
- value: () => string;
- setValue: (value: string) => void;
- focus: () => void;
- ref: React.RefObject<HTMLTextAreaElement>;
-}
-
-// This is a workaround to prevent the textarea from re-rendering when the inner content changes
-// See https://github.com/ggml-org/llama.cpp/pull/12299
-function useOptimizedTextarea(initValue: string): OptimizedTextareaValue {
- const [savedInitValue, setSavedInitValue] = useState<string>(initValue);
- const textareaRef = useRef<HTMLTextAreaElement>(null);
-
- useEffect(() => {
- if (textareaRef.current && savedInitValue) {
- textareaRef.current.value = savedInitValue;
- setSavedInitValue('');
- }
- }, [textareaRef, savedInitValue, setSavedInitValue]);
-
- return {
- value: () => {
- return textareaRef.current?.value ?? savedInitValue;
- },
- setValue: (value: string) => {
- if (textareaRef.current) {
- textareaRef.current.value = value;
- }
- },
- focus: () => {
- if (textareaRef.current) {
- // focus and move the cursor to the end
- textareaRef.current.focus();
- textareaRef.current.selectionStart = textareaRef.current.value.length;
- }
- },
- ref: textareaRef,
- };
-}
diff --git a/examples/server/webui/src/components/useChatTextarea.ts b/examples/server/webui/src/components/useChatTextarea.ts
new file mode 100644
index 0000000000000..42b128194646f
--- /dev/null
+++ b/examples/server/webui/src/components/useChatTextarea.ts
@@ -0,0 +1,96 @@
+import { useEffect, useRef, useState, useCallback } from 'react';
+
+// Media Query for detecting "large" screens (matching Tailwind's lg: breakpoint)
+const LARGE_SCREEN_MQ = '(min-width: 1024px)';
+
+// Calculates and sets the textarea height based on its scrollHeight
+const adjustTextareaHeight = (textarea: HTMLTextAreaElement | null) => {
+ if (!textarea) return;
+
+ // Only perform auto-sizing on large screens
+ if (!window.matchMedia(LARGE_SCREEN_MQ).matches) {
+ // On small screens, reset inline height and max-height styles.
+ // This allows CSS (e.g., `rows` attribute or classes) to control the height,
+ // and enables manual resizing if `resize-vertical` is set.
+ textarea.style.height = ''; // Use 'auto' or '' to reset
+ textarea.style.maxHeight = '';
+ return; // Do not adjust height programmatically on small screens
+ }
+
+ const computedStyle = window.getComputedStyle(textarea);
+ // Get the max-height specified by CSS (e.g., from `lg:max-h-48`)
+ const currentMaxHeight = computedStyle.maxHeight;
+
+ // Temporarily remove max-height to allow scrollHeight to be calculated correctly
+ textarea.style.maxHeight = 'none';
+ // Reset height to 'auto' to measure the actual scrollHeight needed
+ textarea.style.height = 'auto';
+ // Set the height to the calculated scrollHeight
+ textarea.style.height = `${textarea.scrollHeight}px`;
+ // Re-apply the original max-height from CSS to enforce the limit
+ textarea.style.maxHeight = currentMaxHeight;
+};
+
+// Interface describing the API returned by the hook
+export interface ChatTextareaApi {
+ value: () => string;
+ setValue: (value: string) => void;
+ focus: () => void;
+ ref: React.RefObject<HTMLTextAreaElement>;
+ onInput: (event: React.FormEvent<HTMLTextAreaElement>) => void; // Input handler
+}
+
+// This is a workaround to prevent the textarea from re-rendering when the inner content changes
+// See https://github.com/ggml-org/llama.cpp/pull/12299
+// combined now with auto-sizing logic.
+export function useChatTextarea(initValue: string): ChatTextareaApi {
+ const [savedInitValue, setSavedInitValue] = useState<string>(initValue);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ // Effect to set initial value and height on mount or when initValue changes
+ useEffect(() => {
+ const textarea = textareaRef.current;
+ if (textarea) {
+ if (typeof savedInitValue === 'string' && savedInitValue.length > 0) {
+ textarea.value = savedInitValue;
+ // Call adjustTextareaHeight - it will check screen size internally
+ setTimeout(() => adjustTextareaHeight(textarea), 0);
+ setSavedInitValue(''); // Reset after applying
+ } else {
+ // Adjust height even if there's no initial value (for initial render)
+ setTimeout(() => adjustTextareaHeight(textarea), 0);
+ }
+ }
+ }, [textareaRef, savedInitValue]); // Depend on ref and savedInitValue
+
+ const handleInput = useCallback(
+ (event: React.FormEvent<HTMLTextAreaElement>) => {
+ // Call adjustTextareaHeight on every input - it will decide whether to act
+ adjustTextareaHeight(event.currentTarget);
+ },
+ []
+ );
+
+ return {
+ // Method to get the current value directly from the textarea
+ value: () => {
+ return textareaRef.current?.value ?? '';
+ },
+ // Method to programmatically set the value and trigger height adjustment
+ setValue: (value: string) => {
+ const textarea = textareaRef.current;
+ if (textarea) {
+ textarea.value = value;
+ // Call adjustTextareaHeight - it will check screen size internally
+ setTimeout(() => adjustTextareaHeight(textarea), 0);
+ }
+ },
+ focus: () => {
+ if (textareaRef.current) {
+ textareaRef.current.focus();
+ }
+ },
+ ref: textareaRef,
+ onInput: handleInput,
+ };
+}
diff --git a/examples/server/webui/src/utils/llama-vscode.ts b/examples/server/webui/src/utils/llama-vscode.ts
index 5749c14bfdc99..c45b0d3973c2c 100644
--- a/examples/server/webui/src/utils/llama-vscode.ts
+++ b/examples/server/webui/src/utils/llama-vscode.ts
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { MessageExtraContext } from './types';
-import { OptimizedTextareaValue } from '../components/ChatScreen';
+import { ChatTextareaApi } from '../components/useChatTextarea.ts';
// Extra context when using llama.cpp WebUI from llama-vscode, inside an iframe
// Ref: https://github.com/ggml-org/llama.cpp/pull/11940
@@ -15,7 +15,7 @@ interface SetTextEvData {
* window.postMessage({ command: 'setText', text: 'Spot the syntax error', context: 'def test()\n return 123' }, '*');
*/
-export const useVSCodeContext = (textarea: OptimizedTextareaValue) => {
+export const useVSCodeContext = (textarea: ChatTextareaApi) => {
const [extraContext, setExtraContext] = useState<MessageExtraContext | null>(
null
);
| diff --git a/examples/server/public/index.html.gz b/examples/server/public/index.html.gz
index 941815c22efb0..674e227571e2d 100644
Binary files a/examples/server/public/index.html.gz and b/examples/server/public/index.html.gz differ
diff --git a/examples/server/webui/src/components/ChatScreen.tsx b/examples/server/webui/src/components/ChatScreen.tsx
index d12b06e125e5a..29ab5ea64f76f 100644
--- a/examples/server/webui/src/components/ChatScreen.tsx
+++ b/examples/server/webui/src/components/ChatScreen.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { CallbackGeneratedChunk, useAppContext } from '../utils/app.context';
import ChatMessage from './ChatMessage';
import { CanvasType, Message, PendingMessage } from '../utils/types';
@@ -6,6 +6,7 @@ import { classNames, cleanCurrentUrl, throttle } from '../utils/misc';
import CanvasPyInterpreter from './CanvasPyInterpreter';
import StorageUtils from '../utils/storage';
import { useVSCodeContext } from '../utils/llama-vscode';
+import { useChatTextarea, ChatTextareaApi } from './useChatTextarea.ts';
/**
* A message display is a message node with additional information for rendering.
@@ -99,7 +100,8 @@ export default function ChatScreen() {
canvasData,
replaceMessageAndGenerate,
} = useAppContext();
- const textarea = useOptimizedTextarea(prefilledMsg.content());
+ const textarea: ChatTextareaApi = useChatTextarea(prefilledMsg.content());
const { extraContext, clearExtraContext } = useVSCodeContext(textarea);
// TODO: improve this when we have "upload file" feature
@@ -248,14 +250,16 @@ export default function ChatScreen() {
</div>
{/* chat input */}
- <div className="flex flex-row items-center pt-8 pb-6 sticky bottom-0 bg-base-100">
+ <div className="flex flex-row items-end pt-8 pb-6 sticky bottom-0 bg-base-100">
<textarea
- className="textarea textarea-bordered w-full"
+ // Default (mobile): Enable vertical resize, overflow auto for scrolling if needed
+ // Large screens (lg:): Disable manual resize, apply max-height for autosize limit
+ className="textarea textarea-bordered w-full resize-vertical lg:resize-none lg:max-h-48 lg:overflow-y-auto" // Adjust lg:max-h-48 as needed (e.g., lg:max-h-60)
placeholder="Type a message (Shift+Enter to add a new line)"
ref={textarea.ref}
+ onInput={textarea.onInput} // Hook's input handler (will only resize height on lg+ screens)
onKeyDown={(e) => {
if (e.nativeEvent.isComposing || e.keyCode === 229) return;
- if (e.key === 'Enter' && e.shiftKey) return;
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendNewMessage();
@@ -263,7 +267,11 @@ export default function ChatScreen() {
}}
id="msg-input"
dir="auto"
+ // Set a base height of 2 rows for mobile views
+ rows={2}
></textarea>
{isGenerating(currConvId ?? '') ? (
<button
className="btn btn-neutral ml-2"
@@ -286,43 +294,3 @@ export default function ChatScreen() {
</div>
}
-export interface OptimizedTextareaValue {
- value: () => string;
- setValue: (value: string) => void;
- focus: () => void;
- ref: React.RefObject<HTMLTextAreaElement>;
-// This is a workaround to prevent the textarea from re-rendering when the inner content changes
-function useOptimizedTextarea(initValue: string): OptimizedTextareaValue {
- const [savedInitValue, setSavedInitValue] = useState<string>(initValue);
- const textareaRef = useRef<HTMLTextAreaElement>(null);
- useEffect(() => {
- if (textareaRef.current && savedInitValue) {
- textareaRef.current.value = savedInitValue;
- setSavedInitValue('');
- }, [textareaRef, savedInitValue, setSavedInitValue]);
- return {
- value: () => {
- return textareaRef.current?.value ?? savedInitValue;
- textareaRef.current.value = value;
- focus: () => {
- // focus and move the cursor to the end
- textareaRef.current.focus();
- textareaRef.current.selectionStart = textareaRef.current.value.length;
- ref: textareaRef,
- };
diff --git a/examples/server/webui/src/components/useChatTextarea.ts b/examples/server/webui/src/components/useChatTextarea.ts
new file mode 100644
index 0000000000000..42b128194646f
--- /dev/null
+++ b/examples/server/webui/src/components/useChatTextarea.ts
@@ -0,0 +1,96 @@
+// Media Query for detecting "large" screens (matching Tailwind's lg: breakpoint)
+const LARGE_SCREEN_MQ = '(min-width: 1024px)';
+// Calculates and sets the textarea height based on its scrollHeight
+const adjustTextareaHeight = (textarea: HTMLTextAreaElement | null) => {
+ if (!textarea) return;
+ // Only perform auto-sizing on large screens
+ if (!window.matchMedia(LARGE_SCREEN_MQ).matches) {
+ // On small screens, reset inline height and max-height styles.
+ // This allows CSS (e.g., `rows` attribute or classes) to control the height,
+ // and enables manual resizing if `resize-vertical` is set.
+ textarea.style.height = ''; // Use 'auto' or '' to reset
+ textarea.style.maxHeight = '';
+ return; // Do not adjust height programmatically on small screens
+ }
+ const computedStyle = window.getComputedStyle(textarea);
+ // Get the max-height specified by CSS (e.g., from `lg:max-h-48`)
+ const currentMaxHeight = computedStyle.maxHeight;
+ // Temporarily remove max-height to allow scrollHeight to be calculated correctly
+ textarea.style.maxHeight = 'none';
+ // Reset height to 'auto' to measure the actual scrollHeight needed
+ textarea.style.height = 'auto';
+ // Set the height to the calculated scrollHeight
+ textarea.style.height = `${textarea.scrollHeight}px`;
+ // Re-apply the original max-height from CSS to enforce the limit
+ textarea.style.maxHeight = currentMaxHeight;
+};
+// Interface describing the API returned by the hook
+export interface ChatTextareaApi {
+ value: () => string;
+ setValue: (value: string) => void;
+ focus: () => void;
+ ref: React.RefObject<HTMLTextAreaElement>;
+ onInput: (event: React.FormEvent<HTMLTextAreaElement>) => void; // Input handler
+// This is a workaround to prevent the textarea from re-rendering when the inner content changes
+// See https://github.com/ggml-org/llama.cpp/pull/12299
+// combined now with auto-sizing logic.
+export function useChatTextarea(initValue: string): ChatTextareaApi {
+ const [savedInitValue, setSavedInitValue] = useState<string>(initValue);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ useEffect(() => {
+ const textarea = textareaRef.current;
+ if (textarea) {
+ if (typeof savedInitValue === 'string' && savedInitValue.length > 0) {
+ textarea.value = savedInitValue;
+ setSavedInitValue(''); // Reset after applying
+ } else {
+ // Adjust height even if there's no initial value (for initial render)
+ }
+ }, [textareaRef, savedInitValue]); // Depend on ref and savedInitValue
+ const handleInput = useCallback(
+ (event: React.FormEvent<HTMLTextAreaElement>) => {
+ // Call adjustTextareaHeight on every input - it will decide whether to act
+ adjustTextareaHeight(event.currentTarget);
+ []
+ );
+ return {
+ // Method to get the current value directly from the textarea
+ value: () => {
+ return textareaRef.current?.value ?? '';
+ // Method to programmatically set the value and trigger height adjustment
+ setValue: (value: string) => {
+ const textarea = textareaRef.current;
+ if (textarea) {
+ textarea.value = value;
+ focus: () => {
+ textareaRef.current.focus();
+ onInput: handleInput,
+ };
diff --git a/examples/server/webui/src/utils/llama-vscode.ts b/examples/server/webui/src/utils/llama-vscode.ts
index 5749c14bfdc99..c45b0d3973c2c 100644
--- a/examples/server/webui/src/utils/llama-vscode.ts
+++ b/examples/server/webui/src/utils/llama-vscode.ts
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { MessageExtraContext } from './types';
-import { OptimizedTextareaValue } from '../components/ChatScreen';
+import { ChatTextareaApi } from '../components/useChatTextarea.ts';
// Extra context when using llama.cpp WebUI from llama-vscode, inside an iframe
// Ref: https://github.com/ggml-org/llama.cpp/pull/11940
@@ -15,7 +15,7 @@ interface SetTextEvData {
* window.postMessage({ command: 'setText', text: 'Spot the syntax error', context: 'def test()\n return 123' }, '*');
*/
-export const useVSCodeContext = (textarea: OptimizedTextareaValue) => {
+export const useVSCodeContext = (textarea: ChatTextareaApi) => {
const [extraContext, setExtraContext] = useState<MessageExtraContext | null>(
null | [
"+ // On lg+ screens, the hook will calculate and set the initial height anyway",
"-// See https://github.com/ggml-org/llama.cpp/pull/12299",
"- }",
"- setValue: (value: string) => {",
"+import { useEffect, useRef, useState, useCallback } from 'react';",
"+ // Effect to set initial value and height on mount or when initValue changes",
"+ if (textareaRef.current) {",
"+ ref: textareaRef,"
] | [
56,
76,
85,
92,
113,
162,
201,
205
] | {
"additions": 111,
"author": "characharm",
"deletions": 47,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/12785",
"issue_id": 12785,
"merged_at": "2025-04-08T09:14:59Z",
"omission_probability": 0.1,
"pr_number": 12785,
"repo": "ggml-org/llama.cpp",
"title": " Improve Chat Input with Auto-Sizing Textarea",
"total_changes": 158
} |
797 | diff --git a/convert_hf_to_gguf.py b/convert_hf_to_gguf.py
index 89522dee8b8ad..d277b8c7327c7 100755
--- a/convert_hf_to_gguf.py
+++ b/convert_hf_to_gguf.py
@@ -4934,10 +4934,25 @@ class Glm4Model(Model):
model_arch = gguf.MODEL_ARCH.GLM4
def set_vocab(self):
- self._set_vocab_gpt2()
+ from transformers import AutoTokenizer
+ tokenizer = AutoTokenizer.from_pretrained(self.dir_model, trust_remote_code=True)
+ special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)
+ tokens, toktypes, tokpre = self.get_vocab_base()
+ self.gguf_writer.add_tokenizer_model("gpt2")
+ self.gguf_writer.add_tokenizer_pre(tokpre)
+ self.gguf_writer.add_token_list(tokens)
+ self.gguf_writer.add_token_types(toktypes)
+ special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)
+ special_vocab._set_special_token("eos", tokenizer.get_added_vocab()["<|endoftext|>"])
+ special_vocab._set_special_token("eot", tokenizer.get_added_vocab()["<|user|>"])
+ special_vocab._set_special_token("unk", tokenizer.get_added_vocab()["<|endoftext|>"])
+ special_vocab._set_special_token("bos", tokenizer.get_added_vocab()["[gMASK]"])
+ special_vocab.add_to_gguf(self.gguf_writer)
def set_gguf_parameters(self):
super().set_gguf_parameters()
+ rope_dim = self.hparams["head_dim"]
+ self.gguf_writer.add_rope_dimension_count(int(rope_dim * self.hparams.get("partial_rotary_factor", 0.5)))
if self.hparams.get("rope_scaling") is not None and "factor" in self.hparams["rope_scaling"]:
if self.hparams["rope_scaling"].get("type") == "yarn":
self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.YARN)
| diff --git a/convert_hf_to_gguf.py b/convert_hf_to_gguf.py
index 89522dee8b8ad..d277b8c7327c7 100755
--- a/convert_hf_to_gguf.py
+++ b/convert_hf_to_gguf.py
@@ -4934,10 +4934,25 @@ class Glm4Model(Model):
model_arch = gguf.MODEL_ARCH.GLM4
def set_vocab(self):
+ from transformers import AutoTokenizer
+ tokenizer = AutoTokenizer.from_pretrained(self.dir_model, trust_remote_code=True)
+ tokens, toktypes, tokpre = self.get_vocab_base()
+ self.gguf_writer.add_tokenizer_model("gpt2")
+ self.gguf_writer.add_tokenizer_pre(tokpre)
+ self.gguf_writer.add_token_list(tokens)
+ self.gguf_writer.add_token_types(toktypes)
+ special_vocab._set_special_token("eos", tokenizer.get_added_vocab()["<|endoftext|>"])
+ special_vocab._set_special_token("eot", tokenizer.get_added_vocab()["<|user|>"])
+ special_vocab._set_special_token("bos", tokenizer.get_added_vocab()["[gMASK]"])
+ special_vocab.add_to_gguf(self.gguf_writer)
def set_gguf_parameters(self):
super().set_gguf_parameters()
+ rope_dim = self.hparams["head_dim"]
+ self.gguf_writer.add_rope_dimension_count(int(rope_dim * self.hparams.get("partial_rotary_factor", 0.5)))
if self.hparams.get("rope_scaling") is not None and "factor" in self.hparams["rope_scaling"]:
if self.hparams["rope_scaling"].get("type") == "yarn":
self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.YARN) | [
"- self._set_vocab_gpt2()",
"+ special_vocab._set_special_token(\"unk\", tokenizer.get_added_vocab()[\"<|endoftext|>\"])"
] | [
8,
20
] | {
"additions": 16,
"author": "piDack",
"deletions": 1,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/13021",
"issue_id": 13021,
"merged_at": "2025-04-23T14:59:14Z",
"omission_probability": 0.1,
"pr_number": 13021,
"repo": "ggml-org/llama.cpp",
"title": "Append mult-eos,half-rope,bos to GLM4-0414 and Z",
"total_changes": 17
} |
798 | diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh
index 532358018f410..3cb2015520ba1 100644
--- a/ggml/src/ggml-cuda/mmq.cuh
+++ b/ggml/src/ggml-cuda/mmq.cuh
@@ -155,25 +155,27 @@ static constexpr __device__ int get_mmq_y_device() {
#define MMQ_DP4A_TXS_Q6_K tile_x_sizes{mmq_y*WARP_SIZE*2 + mmq_y, mmq_y*WARP_SIZE/QI6_K + mmq_y/QI6_K, mmq_y*WARP_SIZE/8 + mmq_y/8}
static constexpr __host__ __device__ tile_x_sizes mmq_get_dp4a_tile_x_sizes(ggml_type type, int mmq_y) {
- return type == GGML_TYPE_Q4_0 ? MMQ_DP4A_TXS_Q4_0 :
- type == GGML_TYPE_Q4_1 ? MMQ_DP4A_TXS_Q4_1 :
- type == GGML_TYPE_Q5_0 ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_Q5_1 ? MMQ_DP4A_TXS_Q8_1 :
- type == GGML_TYPE_Q8_0 ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_Q2_K ? MMQ_DP4A_TXS_Q2_K :
- type == GGML_TYPE_Q3_K ? MMQ_DP4A_TXS_Q3_K :
- type == GGML_TYPE_Q4_K ? MMQ_DP4A_TXS_Q4_K :
- type == GGML_TYPE_Q5_K ? MMQ_DP4A_TXS_Q5_K :
- type == GGML_TYPE_Q6_K ? MMQ_DP4A_TXS_Q6_K :
- type == GGML_TYPE_IQ2_XXS ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_IQ2_XS ? MMQ_DP4A_TXS_Q8_0_16 :
- type == GGML_TYPE_IQ2_S ? MMQ_DP4A_TXS_Q8_0_16 :
- type == GGML_TYPE_IQ3_XXS ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_IQ3_S ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_IQ1_S ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_IQ4_XS ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_IQ4_NL ? MMQ_DP4A_TXS_Q8_0 :
- tile_x_sizes{0, 0, 0};
+ switch (type) {
+ case GGML_TYPE_Q4_0: return MMQ_DP4A_TXS_Q4_0;
+ case GGML_TYPE_Q4_1: return MMQ_DP4A_TXS_Q4_1;
+ case GGML_TYPE_Q5_0: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_Q5_1: return MMQ_DP4A_TXS_Q8_1;
+ case GGML_TYPE_Q8_0: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_Q2_K: return MMQ_DP4A_TXS_Q2_K;
+ case GGML_TYPE_Q3_K: return MMQ_DP4A_TXS_Q3_K;
+ case GGML_TYPE_Q4_K: return MMQ_DP4A_TXS_Q4_K;
+ case GGML_TYPE_Q5_K: return MMQ_DP4A_TXS_Q5_K;
+ case GGML_TYPE_Q6_K: return MMQ_DP4A_TXS_Q6_K;
+ case GGML_TYPE_IQ2_XXS: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ2_XS: return MMQ_DP4A_TXS_Q8_0_16;
+ case GGML_TYPE_IQ2_S: return MMQ_DP4A_TXS_Q8_0_16;
+ case GGML_TYPE_IQ3_XXS: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ3_S: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ1_S: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ4_XS: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ4_NL: return MMQ_DP4A_TXS_Q8_0;
+ default: return tile_x_sizes{0, 0, 0};
+ }
}
#define MMQ_MMA_TILE_X_K_Q8_0 (2*WARP_SIZE + 2*WARP_SIZE/QI8_0 + 4)
@@ -189,25 +191,27 @@ static_assert(MMQ_MMA_TILE_X_K_Q3_K % 8 == 4, "Wrong padding.");
static_assert(MMQ_MMA_TILE_X_K_Q6_K % 8 == 4, "Wrong padding.");
static constexpr __host__ __device__ int mmq_get_mma_tile_x_k(ggml_type type) {
- return type == GGML_TYPE_Q4_0 ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_Q4_1 ? MMQ_MMA_TILE_X_K_Q8_1 :
- type == GGML_TYPE_Q5_0 ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_Q5_1 ? MMQ_MMA_TILE_X_K_Q8_1 :
- type == GGML_TYPE_Q8_0 ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_Q2_K ? MMQ_MMA_TILE_X_K_Q2_K :
- type == GGML_TYPE_Q3_K ? MMQ_MMA_TILE_X_K_Q3_K :
- type == GGML_TYPE_Q4_K ? MMQ_MMA_TILE_X_K_Q8_1 :
- type == GGML_TYPE_Q5_K ? MMQ_MMA_TILE_X_K_Q8_1 :
- type == GGML_TYPE_Q6_K ? MMQ_MMA_TILE_X_K_Q6_K :
- type == GGML_TYPE_IQ2_XXS ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ2_XS ? MMQ_MMA_TILE_X_K_Q3_K :
- type == GGML_TYPE_IQ2_S ? MMQ_MMA_TILE_X_K_Q3_K :
- type == GGML_TYPE_IQ3_XXS ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ3_S ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ1_S ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ4_XS ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ4_NL ? MMQ_MMA_TILE_X_K_Q8_0 :
- 0;
+ switch (type) {
+ case GGML_TYPE_Q4_0: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_Q4_1: return MMQ_MMA_TILE_X_K_Q8_1;
+ case GGML_TYPE_Q5_0: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_Q5_1: return MMQ_MMA_TILE_X_K_Q8_1;
+ case GGML_TYPE_Q8_0: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_Q2_K: return MMQ_MMA_TILE_X_K_Q2_K;
+ case GGML_TYPE_Q3_K: return MMQ_MMA_TILE_X_K_Q3_K;
+ case GGML_TYPE_Q4_K: return MMQ_MMA_TILE_X_K_Q8_1;
+ case GGML_TYPE_Q5_K: return MMQ_MMA_TILE_X_K_Q8_1;
+ case GGML_TYPE_Q6_K: return MMQ_MMA_TILE_X_K_Q6_K;
+ case GGML_TYPE_IQ2_XXS: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ2_XS: return MMQ_MMA_TILE_X_K_Q3_K;
+ case GGML_TYPE_IQ2_S: return MMQ_MMA_TILE_X_K_Q3_K;
+ case GGML_TYPE_IQ3_XXS: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ3_S: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ1_S: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ4_XS: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ4_NL: return MMQ_MMA_TILE_X_K_Q8_0;
+ default: return 0;
+ }
}
#define MMQ_TILE_Y_K (WARP_SIZE + WARP_SIZE/QI8_1)
diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu
index cac04916cd8f0..d846e35a6a26d 100644
--- a/ggml/src/ggml-cuda/mmvq.cu
+++ b/ggml/src/ggml-cuda/mmvq.cu
@@ -7,47 +7,51 @@
typedef float (*vec_dot_q_cuda_t)(const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs);
static constexpr __device__ vec_dot_q_cuda_t get_vec_dot_q_cuda(ggml_type type) {
- return type == GGML_TYPE_Q4_0 ? vec_dot_q4_0_q8_1 :
- type == GGML_TYPE_Q4_1 ? vec_dot_q4_1_q8_1 :
- type == GGML_TYPE_Q5_0 ? vec_dot_q5_0_q8_1 :
- type == GGML_TYPE_Q5_1 ? vec_dot_q5_1_q8_1 :
- type == GGML_TYPE_Q8_0 ? vec_dot_q8_0_q8_1 :
- type == GGML_TYPE_Q2_K ? vec_dot_q2_K_q8_1 :
- type == GGML_TYPE_Q3_K ? vec_dot_q3_K_q8_1 :
- type == GGML_TYPE_Q4_K ? vec_dot_q4_K_q8_1 :
- type == GGML_TYPE_Q5_K ? vec_dot_q5_K_q8_1 :
- type == GGML_TYPE_Q6_K ? vec_dot_q6_K_q8_1 :
- type == GGML_TYPE_IQ2_XXS ? vec_dot_iq2_xxs_q8_1 :
- type == GGML_TYPE_IQ2_XS ? vec_dot_iq2_xs_q8_1 :
- type == GGML_TYPE_IQ2_S ? vec_dot_iq2_s_q8_1 :
- type == GGML_TYPE_IQ3_XXS ? vec_dot_iq3_xxs_q8_1 :
- type == GGML_TYPE_IQ1_S ? vec_dot_iq1_s_q8_1 :
- type == GGML_TYPE_IQ1_M ? vec_dot_iq1_m_q8_1 :
- type == GGML_TYPE_IQ4_NL ? vec_dot_iq4_nl_q8_1 :
- type == GGML_TYPE_IQ4_XS ? vec_dot_iq4_xs_q8_1 :
- type == GGML_TYPE_IQ3_S ? vec_dot_iq3_s_q8_1 :
- nullptr;
+ switch (type) {
+ case GGML_TYPE_Q4_0: return vec_dot_q4_0_q8_1;
+ case GGML_TYPE_Q4_1: return vec_dot_q4_1_q8_1;
+ case GGML_TYPE_Q5_0: return vec_dot_q5_0_q8_1;
+ case GGML_TYPE_Q5_1: return vec_dot_q5_1_q8_1;
+ case GGML_TYPE_Q8_0: return vec_dot_q8_0_q8_1;
+ case GGML_TYPE_Q2_K: return vec_dot_q2_K_q8_1;
+ case GGML_TYPE_Q3_K: return vec_dot_q3_K_q8_1;
+ case GGML_TYPE_Q4_K: return vec_dot_q4_K_q8_1;
+ case GGML_TYPE_Q5_K: return vec_dot_q5_K_q8_1;
+ case GGML_TYPE_Q6_K: return vec_dot_q6_K_q8_1;
+ case GGML_TYPE_IQ2_XXS: return vec_dot_iq2_xxs_q8_1;
+ case GGML_TYPE_IQ2_XS: return vec_dot_iq2_xs_q8_1;
+ case GGML_TYPE_IQ2_S: return vec_dot_iq2_s_q8_1;
+ case GGML_TYPE_IQ3_XXS: return vec_dot_iq3_xxs_q8_1;
+ case GGML_TYPE_IQ1_S: return vec_dot_iq1_s_q8_1;
+ case GGML_TYPE_IQ1_M: return vec_dot_iq1_m_q8_1;
+ case GGML_TYPE_IQ4_NL: return vec_dot_iq4_nl_q8_1;
+ case GGML_TYPE_IQ4_XS: return vec_dot_iq4_xs_q8_1;
+ case GGML_TYPE_IQ3_S: return vec_dot_iq3_s_q8_1;
+ default: return nullptr;
+ }
}
static constexpr __device__ int get_vdr_mmvq(ggml_type type) {
- return type == GGML_TYPE_Q4_0 ? VDR_Q4_0_Q8_1_MMVQ :
- type == GGML_TYPE_Q4_1 ? VDR_Q4_1_Q8_1_MMVQ :
- type == GGML_TYPE_Q5_0 ? VDR_Q5_0_Q8_1_MMVQ :
- type == GGML_TYPE_Q5_1 ? VDR_Q5_1_Q8_1_MMVQ :
- type == GGML_TYPE_Q8_0 ? VDR_Q8_0_Q8_1_MMVQ :
- type == GGML_TYPE_Q2_K ? VDR_Q2_K_Q8_1_MMVQ :
- type == GGML_TYPE_Q3_K ? VDR_Q3_K_Q8_1_MMVQ :
- type == GGML_TYPE_Q4_K ? VDR_Q4_K_Q8_1_MMVQ :
- type == GGML_TYPE_Q5_K ? VDR_Q5_K_Q8_1_MMVQ :
- type == GGML_TYPE_Q6_K ? VDR_Q6_K_Q8_1_MMVQ :
- type == GGML_TYPE_IQ2_XXS ? VDR_IQ2_XXS_Q8_1_MMVQ :
- type == GGML_TYPE_IQ2_XS ? VDR_IQ2_XS_Q8_1_MMVQ :
- type == GGML_TYPE_IQ2_S ? VDR_IQ2_S_Q8_1_MMVQ :
- type == GGML_TYPE_IQ3_XXS ? VDR_IQ3_XXS_Q8_1_MMVQ :
- type == GGML_TYPE_IQ3_S ? VDR_IQ3_S_Q8_1_MMVQ :
- type == GGML_TYPE_IQ4_NL ? VDR_IQ4_NL_Q8_1_MMVQ :
- type == GGML_TYPE_IQ4_XS ? VDR_IQ4_XS_Q8_1_MMVQ :
- 1;
+ switch (type) {
+ case GGML_TYPE_Q4_0: return VDR_Q4_0_Q8_1_MMVQ;
+ case GGML_TYPE_Q4_1: return VDR_Q4_1_Q8_1_MMVQ;
+ case GGML_TYPE_Q5_0: return VDR_Q5_0_Q8_1_MMVQ;
+ case GGML_TYPE_Q5_1: return VDR_Q5_1_Q8_1_MMVQ;
+ case GGML_TYPE_Q8_0: return VDR_Q8_0_Q8_1_MMVQ;
+ case GGML_TYPE_Q2_K: return VDR_Q2_K_Q8_1_MMVQ;
+ case GGML_TYPE_Q3_K: return VDR_Q3_K_Q8_1_MMVQ;
+ case GGML_TYPE_Q4_K: return VDR_Q4_K_Q8_1_MMVQ;
+ case GGML_TYPE_Q5_K: return VDR_Q5_K_Q8_1_MMVQ;
+ case GGML_TYPE_Q6_K: return VDR_Q6_K_Q8_1_MMVQ;
+ case GGML_TYPE_IQ2_XXS: return VDR_IQ2_XXS_Q8_1_MMVQ;
+ case GGML_TYPE_IQ2_XS: return VDR_IQ2_XS_Q8_1_MMVQ;
+ case GGML_TYPE_IQ2_S: return VDR_IQ2_S_Q8_1_MMVQ;
+ case GGML_TYPE_IQ3_XXS: return VDR_IQ3_XXS_Q8_1_MMVQ;
+ case GGML_TYPE_IQ3_S: return VDR_IQ3_S_Q8_1_MMVQ;
+ case GGML_TYPE_IQ4_NL: return VDR_IQ4_NL_Q8_1_MMVQ;
+ case GGML_TYPE_IQ4_XS: return VDR_IQ4_XS_Q8_1_MMVQ;
+ default: return 1;
+ }
}
enum mmvq_parameter_table_id {
| diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh
index 532358018f410..3cb2015520ba1 100644
--- a/ggml/src/ggml-cuda/mmq.cuh
+++ b/ggml/src/ggml-cuda/mmq.cuh
@@ -155,25 +155,27 @@ static constexpr __device__ int get_mmq_y_device() {
#define MMQ_DP4A_TXS_Q6_K tile_x_sizes{mmq_y*WARP_SIZE*2 + mmq_y, mmq_y*WARP_SIZE/QI6_K + mmq_y/QI6_K, mmq_y*WARP_SIZE/8 + mmq_y/8}
static constexpr __host__ __device__ tile_x_sizes mmq_get_dp4a_tile_x_sizes(ggml_type type, int mmq_y) {
- return type == GGML_TYPE_Q4_0 ? MMQ_DP4A_TXS_Q4_0 :
- type == GGML_TYPE_Q4_1 ? MMQ_DP4A_TXS_Q4_1 :
- type == GGML_TYPE_Q5_0 ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_Q5_1 ? MMQ_DP4A_TXS_Q8_1 :
- type == GGML_TYPE_Q8_0 ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_Q2_K ? MMQ_DP4A_TXS_Q2_K :
- type == GGML_TYPE_Q3_K ? MMQ_DP4A_TXS_Q3_K :
- type == GGML_TYPE_Q5_K ? MMQ_DP4A_TXS_Q5_K :
- type == GGML_TYPE_Q6_K ? MMQ_DP4A_TXS_Q6_K :
- type == GGML_TYPE_IQ2_XXS ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_IQ2_XS ? MMQ_DP4A_TXS_Q8_0_16 :
- type == GGML_TYPE_IQ2_S ? MMQ_DP4A_TXS_Q8_0_16 :
- type == GGML_TYPE_IQ3_XXS ? MMQ_DP4A_TXS_Q8_0 :
- type == GGML_TYPE_IQ4_NL ? MMQ_DP4A_TXS_Q8_0 :
- tile_x_sizes{0, 0, 0};
+ case GGML_TYPE_Q4_0: return MMQ_DP4A_TXS_Q4_0;
+ case GGML_TYPE_Q4_1: return MMQ_DP4A_TXS_Q4_1;
+ case GGML_TYPE_Q5_0: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_Q5_1: return MMQ_DP4A_TXS_Q8_1;
+ case GGML_TYPE_Q8_0: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_Q2_K: return MMQ_DP4A_TXS_Q2_K;
+ case GGML_TYPE_Q3_K: return MMQ_DP4A_TXS_Q3_K;
+ case GGML_TYPE_Q5_K: return MMQ_DP4A_TXS_Q5_K;
+ case GGML_TYPE_Q6_K: return MMQ_DP4A_TXS_Q6_K;
+ case GGML_TYPE_IQ2_XXS: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ2_XS: return MMQ_DP4A_TXS_Q8_0_16;
+ case GGML_TYPE_IQ2_S: return MMQ_DP4A_TXS_Q8_0_16;
+ case GGML_TYPE_IQ3_XXS: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ3_S: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ1_S: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ4_XS: return MMQ_DP4A_TXS_Q8_0;
+ case GGML_TYPE_IQ4_NL: return MMQ_DP4A_TXS_Q8_0;
+ default: return tile_x_sizes{0, 0, 0};
#define MMQ_MMA_TILE_X_K_Q8_0 (2*WARP_SIZE + 2*WARP_SIZE/QI8_0 + 4)
@@ -189,25 +191,27 @@ static_assert(MMQ_MMA_TILE_X_K_Q3_K % 8 == 4, "Wrong padding.");
static_assert(MMQ_MMA_TILE_X_K_Q6_K % 8 == 4, "Wrong padding.");
static constexpr __host__ __device__ int mmq_get_mma_tile_x_k(ggml_type type) {
- return type == GGML_TYPE_Q4_0 ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_Q4_1 ? MMQ_MMA_TILE_X_K_Q8_1 :
- type == GGML_TYPE_Q5_0 ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_Q5_1 ? MMQ_MMA_TILE_X_K_Q8_1 :
- type == GGML_TYPE_Q8_0 ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_Q2_K ? MMQ_MMA_TILE_X_K_Q2_K :
- type == GGML_TYPE_Q3_K ? MMQ_MMA_TILE_X_K_Q3_K :
- type == GGML_TYPE_Q4_K ? MMQ_MMA_TILE_X_K_Q8_1 :
- type == GGML_TYPE_Q5_K ? MMQ_MMA_TILE_X_K_Q8_1 :
- type == GGML_TYPE_Q6_K ? MMQ_MMA_TILE_X_K_Q6_K :
- type == GGML_TYPE_IQ2_XXS ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ2_S ? MMQ_MMA_TILE_X_K_Q3_K :
- type == GGML_TYPE_IQ3_XXS ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ3_S ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ1_S ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ4_XS ? MMQ_MMA_TILE_X_K_Q8_0 :
- type == GGML_TYPE_IQ4_NL ? MMQ_MMA_TILE_X_K_Q8_0 :
- 0;
+ case GGML_TYPE_Q5_0: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_Q5_1: return MMQ_MMA_TILE_X_K_Q8_1;
+ case GGML_TYPE_Q2_K: return MMQ_MMA_TILE_X_K_Q2_K;
+ case GGML_TYPE_Q3_K: return MMQ_MMA_TILE_X_K_Q3_K;
+ case GGML_TYPE_Q4_K: return MMQ_MMA_TILE_X_K_Q8_1;
+ case GGML_TYPE_Q5_K: return MMQ_MMA_TILE_X_K_Q8_1;
+ case GGML_TYPE_Q6_K: return MMQ_MMA_TILE_X_K_Q6_K;
+ case GGML_TYPE_IQ2_XXS: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ2_XS: return MMQ_MMA_TILE_X_K_Q3_K;
+ case GGML_TYPE_IQ2_S: return MMQ_MMA_TILE_X_K_Q3_K;
+ case GGML_TYPE_IQ3_XXS: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ3_S: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ1_S: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ4_XS: return MMQ_MMA_TILE_X_K_Q8_0;
+ case GGML_TYPE_IQ4_NL: return MMQ_MMA_TILE_X_K_Q8_0;
+ default: return 0;
#define MMQ_TILE_Y_K (WARP_SIZE + WARP_SIZE/QI8_1)
diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu
index cac04916cd8f0..d846e35a6a26d 100644
--- a/ggml/src/ggml-cuda/mmvq.cu
+++ b/ggml/src/ggml-cuda/mmvq.cu
@@ -7,47 +7,51 @@
typedef float (*vec_dot_q_cuda_t)(const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs);
static constexpr __device__ vec_dot_q_cuda_t get_vec_dot_q_cuda(ggml_type type) {
- return type == GGML_TYPE_Q4_0 ? vec_dot_q4_0_q8_1 :
- type == GGML_TYPE_Q4_1 ? vec_dot_q4_1_q8_1 :
- type == GGML_TYPE_Q5_0 ? vec_dot_q5_0_q8_1 :
- type == GGML_TYPE_Q5_1 ? vec_dot_q5_1_q8_1 :
- type == GGML_TYPE_Q8_0 ? vec_dot_q8_0_q8_1 :
- type == GGML_TYPE_Q2_K ? vec_dot_q2_K_q8_1 :
- type == GGML_TYPE_Q3_K ? vec_dot_q3_K_q8_1 :
- type == GGML_TYPE_Q4_K ? vec_dot_q4_K_q8_1 :
- type == GGML_TYPE_Q5_K ? vec_dot_q5_K_q8_1 :
- type == GGML_TYPE_Q6_K ? vec_dot_q6_K_q8_1 :
- type == GGML_TYPE_IQ2_XXS ? vec_dot_iq2_xxs_q8_1 :
- type == GGML_TYPE_IQ2_XS ? vec_dot_iq2_xs_q8_1 :
- type == GGML_TYPE_IQ2_S ? vec_dot_iq2_s_q8_1 :
- type == GGML_TYPE_IQ3_XXS ? vec_dot_iq3_xxs_q8_1 :
- type == GGML_TYPE_IQ1_S ? vec_dot_iq1_s_q8_1 :
- type == GGML_TYPE_IQ1_M ? vec_dot_iq1_m_q8_1 :
- type == GGML_TYPE_IQ4_NL ? vec_dot_iq4_nl_q8_1 :
- type == GGML_TYPE_IQ4_XS ? vec_dot_iq4_xs_q8_1 :
- nullptr;
+ case GGML_TYPE_Q4_0: return vec_dot_q4_0_q8_1;
+ case GGML_TYPE_Q4_1: return vec_dot_q4_1_q8_1;
+ case GGML_TYPE_Q5_0: return vec_dot_q5_0_q8_1;
+ case GGML_TYPE_Q5_1: return vec_dot_q5_1_q8_1;
+ case GGML_TYPE_Q8_0: return vec_dot_q8_0_q8_1;
+ case GGML_TYPE_Q2_K: return vec_dot_q2_K_q8_1;
+ case GGML_TYPE_Q3_K: return vec_dot_q3_K_q8_1;
+ case GGML_TYPE_Q5_K: return vec_dot_q5_K_q8_1;
+ case GGML_TYPE_Q6_K: return vec_dot_q6_K_q8_1;
+ case GGML_TYPE_IQ2_XXS: return vec_dot_iq2_xxs_q8_1;
+ case GGML_TYPE_IQ3_XXS: return vec_dot_iq3_xxs_q8_1;
+ case GGML_TYPE_IQ1_S: return vec_dot_iq1_s_q8_1;
+ case GGML_TYPE_IQ1_M: return vec_dot_iq1_m_q8_1;
+ case GGML_TYPE_IQ4_NL: return vec_dot_iq4_nl_q8_1;
+ case GGML_TYPE_IQ4_XS: return vec_dot_iq4_xs_q8_1;
+ case GGML_TYPE_IQ3_S: return vec_dot_iq3_s_q8_1;
+ default: return nullptr;
static constexpr __device__ int get_vdr_mmvq(ggml_type type) {
- return type == GGML_TYPE_Q4_0 ? VDR_Q4_0_Q8_1_MMVQ :
- type == GGML_TYPE_Q4_1 ? VDR_Q4_1_Q8_1_MMVQ :
- type == GGML_TYPE_Q5_0 ? VDR_Q5_0_Q8_1_MMVQ :
- type == GGML_TYPE_Q5_1 ? VDR_Q5_1_Q8_1_MMVQ :
- type == GGML_TYPE_Q8_0 ? VDR_Q8_0_Q8_1_MMVQ :
- type == GGML_TYPE_Q2_K ? VDR_Q2_K_Q8_1_MMVQ :
- type == GGML_TYPE_Q3_K ? VDR_Q3_K_Q8_1_MMVQ :
- type == GGML_TYPE_Q4_K ? VDR_Q4_K_Q8_1_MMVQ :
- type == GGML_TYPE_Q5_K ? VDR_Q5_K_Q8_1_MMVQ :
- type == GGML_TYPE_Q6_K ? VDR_Q6_K_Q8_1_MMVQ :
- type == GGML_TYPE_IQ2_XXS ? VDR_IQ2_XXS_Q8_1_MMVQ :
- type == GGML_TYPE_IQ2_XS ? VDR_IQ2_XS_Q8_1_MMVQ :
- type == GGML_TYPE_IQ2_S ? VDR_IQ2_S_Q8_1_MMVQ :
- type == GGML_TYPE_IQ4_NL ? VDR_IQ4_NL_Q8_1_MMVQ :
- type == GGML_TYPE_IQ4_XS ? VDR_IQ4_XS_Q8_1_MMVQ :
- 1;
+ case GGML_TYPE_Q4_0: return VDR_Q4_0_Q8_1_MMVQ;
+ case GGML_TYPE_Q4_1: return VDR_Q4_1_Q8_1_MMVQ;
+ case GGML_TYPE_Q5_0: return VDR_Q5_0_Q8_1_MMVQ;
+ case GGML_TYPE_Q5_1: return VDR_Q5_1_Q8_1_MMVQ;
+ case GGML_TYPE_Q8_0: return VDR_Q8_0_Q8_1_MMVQ;
+ case GGML_TYPE_Q2_K: return VDR_Q2_K_Q8_1_MMVQ;
+ case GGML_TYPE_Q3_K: return VDR_Q3_K_Q8_1_MMVQ;
+ case GGML_TYPE_Q4_K: return VDR_Q4_K_Q8_1_MMVQ;
+ case GGML_TYPE_Q5_K: return VDR_Q5_K_Q8_1_MMVQ;
+ case GGML_TYPE_IQ2_XXS: return VDR_IQ2_XXS_Q8_1_MMVQ;
+ case GGML_TYPE_IQ2_XS: return VDR_IQ2_XS_Q8_1_MMVQ;
+ case GGML_TYPE_IQ2_S: return VDR_IQ2_S_Q8_1_MMVQ;
+ case GGML_TYPE_IQ3_S: return VDR_IQ3_S_Q8_1_MMVQ;
+ case GGML_TYPE_IQ4_NL: return VDR_IQ4_NL_Q8_1_MMVQ;
+ case GGML_TYPE_IQ4_XS: return VDR_IQ4_XS_Q8_1_MMVQ;
+ default: return 1;
enum mmvq_parameter_table_id { | [
"- type == GGML_TYPE_Q4_K ? MMQ_DP4A_TXS_Q4_K :",
"- type == GGML_TYPE_IQ3_S ? MMQ_DP4A_TXS_Q8_0 :",
"- type == GGML_TYPE_IQ1_S ? MMQ_DP4A_TXS_Q8_0 :",
"- type == GGML_TYPE_IQ4_XS ? MMQ_DP4A_TXS_Q8_0 :",
"+ case GGML_TYPE_Q4_K: return MMQ_DP4A_TXS_Q4_K;",
"- type == GGML_TYPE_IQ2_XS ? MMQ_MMA_TILE_X_K_Q3_K :",
"+ case GGML_TYPE_Q4_0: return MMQ_MMA_TILE_X_K_Q8_0;",
"+ case GGML_TYPE_Q4_1: return MMQ_MMA_TILE_X_K_Q8_1;",
"+ case GGML_TYPE_Q8_0: return MMQ_MMA_TILE_X_K_Q8_0;",
"- type == GGML_TYPE_IQ3_S ? vec_dot_iq3_s_q8_1 :",
"+ case GGML_TYPE_Q4_K: return vec_dot_q4_K_q8_1;",
"+ case GGML_TYPE_IQ2_XS: return vec_dot_iq2_xs_q8_1;",
"+ case GGML_TYPE_IQ2_S: return vec_dot_iq2_s_q8_1;",
"- type == GGML_TYPE_IQ3_XXS ? VDR_IQ3_XXS_Q8_1_MMVQ :",
"- type == GGML_TYPE_IQ3_S ? VDR_IQ3_S_Q8_1_MMVQ :",
"+ case GGML_TYPE_Q6_K: return VDR_Q6_K_Q8_1_MMVQ;",
"+ case GGML_TYPE_IQ3_XXS: return VDR_IQ3_XXS_Q8_1_MMVQ;"
] | [
15,
22,
23,
24,
35,
66,
75,
76,
79,
124,
134,
138,
139,
164,
165,
179,
183
] | {
"additions": 84,
"author": "JohannesGaessler",
"deletions": 76,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/13095",
"issue_id": 13095,
"merged_at": "2025-04-24T13:57:10Z",
"omission_probability": 0.1,
"pr_number": 13095,
"repo": "ggml-org/llama.cpp",
"title": "CUDA: use switch statements in constexpr functions",
"total_changes": 160
} |
799 | diff --git a/common/arg.cpp b/common/arg.cpp
index 1cfd0168d95ae..aa8310d119029 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -968,7 +968,6 @@ static void common_params_print_completion(common_params_context & ctx_arg) {
"llama-embedding",
"llama-eval-callback",
"llama-export-lora",
- "llama-gbnf-validator",
"llama-gen-docs",
"llama-gguf",
"llama-gguf-hash",
@@ -988,7 +987,6 @@ static void common_params_print_completion(common_params_context & ctx_arg) {
"llama-perplexity",
"llama-q8dot",
"llama-quantize",
- "llama-quantize-stats",
"llama-qwen2vl-cli",
"llama-retrieval",
"llama-run",
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index 66cfab2c3b796..37476f9043e78 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -21,11 +21,6 @@ else()
add_subdirectory(embedding)
add_subdirectory(eval-callback)
- if (NOT WIN32)
- # disabled on Windows because it uses internal functions not exported with LLAMA_API
- add_subdirectory(gbnf-validator)
- endif()
-
add_subdirectory(gguf-hash)
add_subdirectory(gguf-split)
add_subdirectory(gguf)
@@ -58,10 +53,6 @@ else()
add_subdirectory(convert-llama2c-to-ggml)
add_subdirectory(cvector-generator)
add_subdirectory(export-lora)
- if (NOT WIN32)
- # disabled on Windows because it uses internal functions not exported with LLAMA_API
- add_subdirectory(quantize-stats)
- endif()
add_subdirectory(llava)
if (GGML_RPC)
add_subdirectory(rpc)
diff --git a/examples/gbnf-validator/CMakeLists.txt b/examples/gbnf-validator/CMakeLists.txt
deleted file mode 100644
index d2cb524c0a7f7..0000000000000
--- a/examples/gbnf-validator/CMakeLists.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-set(TARGET llama-gbnf-validator)
-add_executable(${TARGET} gbnf-validator.cpp)
-install(TARGETS ${TARGET} RUNTIME)
-target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
-target_compile_features(${TARGET} PRIVATE cxx_std_17)
diff --git a/examples/quantize-stats/CMakeLists.txt b/examples/quantize-stats/CMakeLists.txt
deleted file mode 100644
index 9a3a0d3cd2dee..0000000000000
--- a/examples/quantize-stats/CMakeLists.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-set(TARGET llama-quantize-stats)
-add_executable(${TARGET} quantize-stats.cpp)
-install(TARGETS ${TARGET} RUNTIME)
-target_link_libraries(${TARGET} PRIVATE llama build_info ${CMAKE_THREAD_LIBS_INIT})
-target_include_directories(${TARGET} PRIVATE ../../common)
-target_compile_features(${TARGET} PRIVATE cxx_std_17)
diff --git a/grammars/README.md b/grammars/README.md
index 935213f5c1849..5aa12acc1bff3 100644
--- a/grammars/README.md
+++ b/grammars/README.md
@@ -112,7 +112,7 @@ You can use GBNF grammars:
- In [llama-server](../examples/server)'s completion endpoints, passed as the `grammar` body field
- In [llama-cli](../examples/main), passed as the `--grammar` & `--grammar-file` flags
-- With [llama-gbnf-validator](../examples/gbnf-validator) tool, to test them against strings.
+- With [test-gbnf-validator](../tests/test-gbnf-validator.cpp), to test them against strings.
## JSON Schemas → GBNF
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 9f7ab13f1e620..1cd316b03e132 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -32,8 +32,9 @@ add_library(llama
unicode.h
)
-target_include_directories(llama PUBLIC . ../include)
-target_compile_features (llama PUBLIC cxx_std_17) # don't bump
+target_include_directories(llama PRIVATE .)
+target_include_directories(llama PUBLIC ../include)
+target_compile_features (llama PRIVATE cxx_std_17) # don't bump
target_link_libraries(llama PUBLIC ggml)
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 2bb210702aef8..ae68275251d01 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -1,5 +1,17 @@
llama_add_compile_flags()
+function(llama_build source)
+ if (DEFINED LLAMA_TEST_NAME)
+ set(TEST_TARGET ${LLAMA_TEST_NAME})
+ else()
+ get_filename_component(TEST_TARGET ${source} NAME_WE)
+ endif()
+
+ add_executable(${TEST_TARGET} ${source})
+ target_link_libraries(${TEST_TARGET} PRIVATE common)
+ install(TARGETS ${TEST_TARGET} RUNTIME)
+endfunction()
+
function(llama_test target)
include(CMakeParseArguments)
set(options)
@@ -36,7 +48,7 @@ endfunction()
# - LABEL: label for the test (defaults to main)
# - ARGS: arguments to pass to the test executable
# - WORKING_DIRECTORY
-function(llama_target_and_test source)
+function(llama_build_and_test source)
include(CMakeParseArguments)
set(options)
set(oneValueArgs NAME LABEL WORKING_DIRECTORY)
@@ -58,6 +70,7 @@ function(llama_target_and_test source)
add_executable(${TEST_TARGET} ${source} get-model.cpp)
install(TARGETS ${TEST_TARGET} RUNTIME)
target_link_libraries(${TEST_TARGET} PRIVATE common)
+
add_test(
NAME ${TEST_TARGET}
WORKING_DIRECTORY ${LLAMA_TEST_WORKING_DIRECTORY}
@@ -68,9 +81,7 @@ function(llama_target_and_test source)
endfunction()
# build test-tokenizer-0 target once and add many tests
-add_executable(test-tokenizer-0 test-tokenizer-0.cpp)
-target_link_libraries(test-tokenizer-0 PRIVATE common)
-install(TARGETS test-tokenizer-0 RUNTIME)
+llama_build(test-tokenizer-0.cpp)
llama_test(test-tokenizer-0 NAME test-tokenizer-0-bert-bge ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-bert-bge.gguf)
llama_test(test-tokenizer-0 NAME test-tokenizer-0-command-r ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-command-r.gguf)
@@ -87,27 +98,27 @@ llama_test(test-tokenizer-0 NAME test-tokenizer-0-refact ARGS ${CMAKE
llama_test(test-tokenizer-0 NAME test-tokenizer-0-starcoder ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-starcoder.gguf)
if (LLAMA_LLGUIDANCE)
- llama_target_and_test(test-grammar-llguidance.cpp ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-llama-bpe.gguf)
+ llama_build_and_test(test-grammar-llguidance.cpp ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-llama-bpe.gguf)
endif ()
if (NOT WIN32)
# these tests are disabled on Windows because they use internal functions not exported with LLAMA_API
- llama_target_and_test(test-sampling.cpp)
- llama_target_and_test(test-grammar-parser.cpp)
- llama_target_and_test(test-grammar-integration.cpp)
- llama_target_and_test(test-llama-grammar.cpp)
- llama_target_and_test(test-chat.cpp)
+ llama_build_and_test(test-sampling.cpp)
+ llama_build_and_test(test-grammar-parser.cpp)
+ llama_build_and_test(test-grammar-integration.cpp)
+ llama_build_and_test(test-llama-grammar.cpp)
+ llama_build_and_test(test-chat.cpp)
# TODO: disabled on loongarch64 because the ggml-ci node lacks Python 3.8
if (NOT ${CMAKE_SYSTEM_PROCESSOR} MATCHES "loongarch64")
- llama_target_and_test(test-json-schema-to-grammar.cpp WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/..)
+ llama_build_and_test(test-json-schema-to-grammar.cpp WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/..)
target_include_directories(test-json-schema-to-grammar PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../examples/server)
endif()
+ llama_build(test-quantize-stats.cpp)
+ llama_build(test-gbnf-validator.cpp)
# build test-tokenizer-1-bpe target once and add many tests
- add_executable(test-tokenizer-1-bpe test-tokenizer-1-bpe.cpp)
- target_link_libraries(test-tokenizer-1-bpe PRIVATE common)
- install(TARGETS test-tokenizer-1-bpe RUNTIME)
+ llama_build(test-tokenizer-1-bpe.cpp)
# TODO: disabled due to slowness
#llama_test(test-tokenizer-1-bpe NAME test-tokenizer-1-aquila ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-aquila.gguf)
@@ -120,37 +131,35 @@ if (NOT WIN32)
#llama_test(test-tokenizer-1-bpe NAME test-tokenizer-1-starcoder ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-starcoder.gguf)
# build test-tokenizer-1-spm target once and add many tests
- add_executable(test-tokenizer-1-spm test-tokenizer-1-spm.cpp)
- target_link_libraries(test-tokenizer-1-spm PRIVATE common)
- install(TARGETS test-tokenizer-1-spm RUNTIME)
+ llama_build(test-tokenizer-1-spm.cpp)
llama_test(test-tokenizer-1-spm NAME test-tokenizer-1-llama-spm ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-llama-spm.gguf)
#llama_test(test-tokenizer-1-spm NAME test-tokenizer-1-baichuan ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-baichuan.gguf)
- # llama_target_and_test(test-double-float.cpp) # SLOW
+ # llama_build_and_test(test-double-float.cpp) # SLOW
endif()
-llama_target_and_test(test-log.cpp)
-llama_target_and_test(test-chat-template.cpp)
+llama_build_and_test(test-log.cpp)
+llama_build_and_test(test-chat-template.cpp)
# this fails on windows (github hosted runner) due to curl DLL not found (exit code 0xc0000135)
if (NOT WIN32)
- llama_target_and_test(test-arg-parser.cpp)
+ llama_build_and_test(test-arg-parser.cpp)
endif()
-# llama_target_and_test(test-opt.cpp) # SLOW
-llama_target_and_test(test-gguf.cpp)
-llama_target_and_test(test-backend-ops.cpp)
+# llama_build_and_test(test-opt.cpp) # SLOW
+llama_build_and_test(test-gguf.cpp)
+llama_build_and_test(test-backend-ops.cpp)
-llama_target_and_test(test-model-load-cancel.cpp LABEL "model")
-llama_target_and_test(test-autorelease.cpp LABEL "model")
+llama_build_and_test(test-model-load-cancel.cpp LABEL "model")
+llama_build_and_test(test-autorelease.cpp LABEL "model")
if (NOT GGML_BACKEND_DL)
# these tests use the backends directly and cannot be built with dynamic loading
- llama_target_and_test(test-barrier.cpp)
- llama_target_and_test(test-quantize-fns.cpp)
- llama_target_and_test(test-quantize-perf.cpp)
- llama_target_and_test(test-rope.cpp)
+ llama_build_and_test(test-barrier.cpp)
+ llama_build_and_test(test-quantize-fns.cpp)
+ llama_build_and_test(test-quantize-perf.cpp)
+ llama_build_and_test(test-rope.cpp)
endif()
diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp
index a0bf6affe5220..fa7aed82dfaa8 100644
--- a/tests/test-chat.cpp
+++ b/tests/test-chat.cpp
@@ -11,8 +11,9 @@
#include <string>
#include "chat.h"
-#include "llama-grammar.h"
-#include "unicode.h"
+
+#include "../src/unicode.h"
+#include "../src/llama-grammar.h"
using json = nlohmann::ordered_json;
diff --git a/examples/gbnf-validator/gbnf-validator.cpp b/tests/test-gbnf-validator.cpp
similarity index 98%
rename from examples/gbnf-validator/gbnf-validator.cpp
rename to tests/test-gbnf-validator.cpp
index a610e6a0b19d7..6547eec32fab4 100644
--- a/examples/gbnf-validator/gbnf-validator.cpp
+++ b/tests/test-gbnf-validator.cpp
@@ -1,5 +1,5 @@
-#include "unicode.h"
-#include "llama-grammar.h"
+#include "../src/unicode.h"
+#include "../src/llama-grammar.h"
#include <cstdio>
#include <cstdlib>
diff --git a/tests/test-grammar-integration.cpp b/tests/test-grammar-integration.cpp
index 89060864894a4..8988c347e3e32 100644
--- a/tests/test-grammar-integration.cpp
+++ b/tests/test-grammar-integration.cpp
@@ -2,10 +2,11 @@
#undef NDEBUG
#endif
-#include "unicode.h"
-#include "llama-grammar.h"
#include "json-schema-to-grammar.h"
+#include "../src/unicode.h"
+#include "../src/llama-grammar.h"
+
#include <cassert>
#include <string>
#include <vector>
diff --git a/tests/test-grammar-llguidance.cpp b/tests/test-grammar-llguidance.cpp
index 3c19220e11964..566b039a07038 100644
--- a/tests/test-grammar-llguidance.cpp
+++ b/tests/test-grammar-llguidance.cpp
@@ -2,7 +2,6 @@
# undef NDEBUG
#endif
-#include "unicode.h"
#include "sampling.h"
#include <cassert>
@@ -84,7 +83,7 @@ static void test(const std::string & test_desc, const std::string & grammar_str,
fprintf(stderr,
"\n NOTE: Debug grammar file generated. To analyze this failure in detail, run the following "
- "command: ./llama-gbnf-validator test-grammar-integration.grammar.gbnf "
+ "command: ./test-gbnf-validator test-grammar-integration.grammar.gbnf "
"test-grammar-integration.string.txt\n\n");
} else {
fprintf(stdout, "✅︎\n");
diff --git a/tests/test-grammar-parser.cpp b/tests/test-grammar-parser.cpp
index 259172d999c78..67821a2d5c609 100644
--- a/tests/test-grammar-parser.cpp
+++ b/tests/test-grammar-parser.cpp
@@ -3,7 +3,9 @@
#endif
#include "llama.h"
-#include "llama-grammar.h"
+
+// TODO: shold not include libllama sources
+#include "../src/llama-grammar.h"
#include <cassert>
diff --git a/tests/test-json-schema-to-grammar.cpp b/tests/test-json-schema-to-grammar.cpp
index 4d78e914269f3..e35134f3cb063 100755
--- a/tests/test-json-schema-to-grammar.cpp
+++ b/tests/test-json-schema-to-grammar.cpp
@@ -4,7 +4,7 @@
#include "json-schema-to-grammar.h"
-#include "llama-grammar.h"
+#include "../src/llama-grammar.h"
#include <cassert>
#include <fstream>
diff --git a/tests/test-llama-grammar.cpp b/tests/test-llama-grammar.cpp
index e2129206be156..cc198f3e3c903 100644
--- a/tests/test-llama-grammar.cpp
+++ b/tests/test-llama-grammar.cpp
@@ -3,7 +3,8 @@
#endif
#include "llama.h"
-#include "llama-grammar.h"
+
+#include "../src/llama-grammar.h"
#include <cassert>
#include <stdexcept>
diff --git a/examples/quantize-stats/quantize-stats.cpp b/tests/test-quantize-stats.cpp
similarity index 99%
rename from examples/quantize-stats/quantize-stats.cpp
rename to tests/test-quantize-stats.cpp
index dd07ab9b37456..db01059119e9b 100644
--- a/examples/quantize-stats/quantize-stats.cpp
+++ b/tests/test-quantize-stats.cpp
@@ -1,8 +1,9 @@
#include "ggml.h"
#include "llama.h"
-#include "llama-model.h"
#include "common.h"
+#include "../src/llama-model.h"
+
#include <algorithm>
#include <cassert>
#include <cinttypes>
diff --git a/tests/test-tokenizer-1-bpe.cpp b/tests/test-tokenizer-1-bpe.cpp
index 55425d88a7e07..b183da47f3cc8 100644
--- a/tests/test-tokenizer-1-bpe.cpp
+++ b/tests/test-tokenizer-1-bpe.cpp
@@ -1,8 +1,9 @@
#include "llama.h"
#include "common.h"
-#include "unicode.h"
#include "console.h"
+#include "../src/unicode.h"
+
#include <cassert>
#include <codecvt>
#include <cstdio>
diff --git a/tests/test-tokenizer-1-spm.cpp b/tests/test-tokenizer-1-spm.cpp
index 9e7b77f31ea12..ba6e94ba8ea57 100644
--- a/tests/test-tokenizer-1-spm.cpp
+++ b/tests/test-tokenizer-1-spm.cpp
@@ -1,8 +1,9 @@
#include "llama.h"
#include "common.h"
-#include "unicode.h"
#include "console.h"
+#include "../src/unicode.h"
+
#include <cassert>
#include <codecvt>
#include <cstdio>
| diff --git a/common/arg.cpp b/common/arg.cpp
index 1cfd0168d95ae..aa8310d119029 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -968,7 +968,6 @@ static void common_params_print_completion(common_params_context & ctx_arg) {
"llama-embedding",
"llama-eval-callback",
"llama-export-lora",
- "llama-gbnf-validator",
"llama-gen-docs",
"llama-gguf",
"llama-gguf-hash",
@@ -988,7 +987,6 @@ static void common_params_print_completion(common_params_context & ctx_arg) {
"llama-perplexity",
"llama-q8dot",
"llama-quantize",
- "llama-quantize-stats",
"llama-qwen2vl-cli",
"llama-retrieval",
"llama-run",
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index 66cfab2c3b796..37476f9043e78 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -21,11 +21,6 @@ else()
add_subdirectory(embedding)
add_subdirectory(eval-callback)
- if (NOT WIN32)
- # disabled on Windows because it uses internal functions not exported with LLAMA_API
-
add_subdirectory(gguf-hash)
add_subdirectory(gguf-split)
add_subdirectory(gguf)
@@ -58,10 +53,6 @@ else()
add_subdirectory(convert-llama2c-to-ggml)
add_subdirectory(cvector-generator)
add_subdirectory(export-lora)
- if (NOT WIN32)
- # disabled on Windows because it uses internal functions not exported with LLAMA_API
- add_subdirectory(quantize-stats)
- endif()
add_subdirectory(llava)
if (GGML_RPC)
add_subdirectory(rpc)
diff --git a/examples/gbnf-validator/CMakeLists.txt b/examples/gbnf-validator/CMakeLists.txt
index d2cb524c0a7f7..0000000000000
--- a/examples/gbnf-validator/CMakeLists.txt
@@ -1,5 +0,0 @@
-set(TARGET llama-gbnf-validator)
-target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
diff --git a/examples/quantize-stats/CMakeLists.txt b/examples/quantize-stats/CMakeLists.txt
index 9a3a0d3cd2dee..0000000000000
--- a/examples/quantize-stats/CMakeLists.txt
@@ -1,6 +0,0 @@
-set(TARGET llama-quantize-stats)
-add_executable(${TARGET} quantize-stats.cpp)
-target_link_libraries(${TARGET} PRIVATE llama build_info ${CMAKE_THREAD_LIBS_INIT})
-target_include_directories(${TARGET} PRIVATE ../../common)
diff --git a/grammars/README.md b/grammars/README.md
index 935213f5c1849..5aa12acc1bff3 100644
--- a/grammars/README.md
+++ b/grammars/README.md
@@ -112,7 +112,7 @@ You can use GBNF grammars:
- In [llama-server](../examples/server)'s completion endpoints, passed as the `grammar` body field
- In [llama-cli](../examples/main), passed as the `--grammar` & `--grammar-file` flags
-- With [llama-gbnf-validator](../examples/gbnf-validator) tool, to test them against strings.
+- With [test-gbnf-validator](../tests/test-gbnf-validator.cpp), to test them against strings.
## JSON Schemas → GBNF
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 9f7ab13f1e620..1cd316b03e132 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -32,8 +32,9 @@ add_library(llama
unicode.h
)
-target_compile_features (llama PUBLIC cxx_std_17) # don't bump
+target_include_directories(llama PRIVATE .)
+target_include_directories(llama PUBLIC ../include)
+target_compile_features (llama PRIVATE cxx_std_17) # don't bump
target_link_libraries(llama PUBLIC ggml)
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 2bb210702aef8..ae68275251d01 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -1,5 +1,17 @@
llama_add_compile_flags()
+function(llama_build source)
+ set(TEST_TARGET ${LLAMA_TEST_NAME})
+ else()
+ get_filename_component(TEST_TARGET ${source} NAME_WE)
+ endif()
+ add_executable(${TEST_TARGET} ${source})
+ target_link_libraries(${TEST_TARGET} PRIVATE common)
+ install(TARGETS ${TEST_TARGET} RUNTIME)
+endfunction()
function(llama_test target)
@@ -36,7 +48,7 @@ endfunction()
# - LABEL: label for the test (defaults to main)
# - ARGS: arguments to pass to the test executable
# - WORKING_DIRECTORY
-function(llama_target_and_test source)
+function(llama_build_and_test source)
set(oneValueArgs NAME LABEL WORKING_DIRECTORY)
@@ -58,6 +70,7 @@ function(llama_target_and_test source)
add_executable(${TEST_TARGET} ${source} get-model.cpp)
install(TARGETS ${TEST_TARGET} RUNTIME)
target_link_libraries(${TEST_TARGET} PRIVATE common)
add_test(
NAME ${TEST_TARGET}
WORKING_DIRECTORY ${LLAMA_TEST_WORKING_DIRECTORY}
@@ -68,9 +81,7 @@ function(llama_target_and_test source)
endfunction()
# build test-tokenizer-0 target once and add many tests
-add_executable(test-tokenizer-0 test-tokenizer-0.cpp)
-target_link_libraries(test-tokenizer-0 PRIVATE common)
-install(TARGETS test-tokenizer-0 RUNTIME)
+llama_build(test-tokenizer-0.cpp)
llama_test(test-tokenizer-0 NAME test-tokenizer-0-bert-bge ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-bert-bge.gguf)
llama_test(test-tokenizer-0 NAME test-tokenizer-0-command-r ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-command-r.gguf)
@@ -87,27 +98,27 @@ llama_test(test-tokenizer-0 NAME test-tokenizer-0-refact ARGS ${CMAKE
llama_test(test-tokenizer-0 NAME test-tokenizer-0-starcoder ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-starcoder.gguf)
if (LLAMA_LLGUIDANCE)
- llama_target_and_test(test-grammar-llguidance.cpp ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-llama-bpe.gguf)
+ llama_build_and_test(test-grammar-llguidance.cpp ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-llama-bpe.gguf)
endif ()
# these tests are disabled on Windows because they use internal functions not exported with LLAMA_API
- llama_target_and_test(test-sampling.cpp)
- llama_target_and_test(test-grammar-parser.cpp)
- llama_target_and_test(test-grammar-integration.cpp)
- llama_target_and_test(test-llama-grammar.cpp)
- llama_target_and_test(test-chat.cpp)
+ llama_build_and_test(test-sampling.cpp)
+ llama_build_and_test(test-grammar-parser.cpp)
+ llama_build_and_test(test-grammar-integration.cpp)
+ llama_build_and_test(test-llama-grammar.cpp)
+ llama_build_and_test(test-chat.cpp)
# TODO: disabled on loongarch64 because the ggml-ci node lacks Python 3.8
if (NOT ${CMAKE_SYSTEM_PROCESSOR} MATCHES "loongarch64")
- llama_target_and_test(test-json-schema-to-grammar.cpp WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/..)
+ llama_build_and_test(test-json-schema-to-grammar.cpp WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/..)
target_include_directories(test-json-schema-to-grammar PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../examples/server)
endif()
+ llama_build(test-gbnf-validator.cpp)
# build test-tokenizer-1-bpe target once and add many tests
- add_executable(test-tokenizer-1-bpe test-tokenizer-1-bpe.cpp)
- target_link_libraries(test-tokenizer-1-bpe PRIVATE common)
- install(TARGETS test-tokenizer-1-bpe RUNTIME)
+ llama_build(test-tokenizer-1-bpe.cpp)
# TODO: disabled due to slowness
#llama_test(test-tokenizer-1-bpe NAME test-tokenizer-1-aquila ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-aquila.gguf)
@@ -120,37 +131,35 @@ if (NOT WIN32)
#llama_test(test-tokenizer-1-bpe NAME test-tokenizer-1-starcoder ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-starcoder.gguf)
# build test-tokenizer-1-spm target once and add many tests
- add_executable(test-tokenizer-1-spm test-tokenizer-1-spm.cpp)
- target_link_libraries(test-tokenizer-1-spm PRIVATE common)
- install(TARGETS test-tokenizer-1-spm RUNTIME)
+ llama_build(test-tokenizer-1-spm.cpp)
llama_test(test-tokenizer-1-spm NAME test-tokenizer-1-llama-spm ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-llama-spm.gguf)
#llama_test(test-tokenizer-1-spm NAME test-tokenizer-1-baichuan ARGS ${CMAKE_CURRENT_SOURCE_DIR}/../models/ggml-vocab-baichuan.gguf)
- # llama_target_and_test(test-double-float.cpp) # SLOW
+ # llama_build_and_test(test-double-float.cpp) # SLOW
-llama_target_and_test(test-log.cpp)
-llama_target_and_test(test-chat-template.cpp)
+llama_build_and_test(test-log.cpp)
+llama_build_and_test(test-chat-template.cpp)
# this fails on windows (github hosted runner) due to curl DLL not found (exit code 0xc0000135)
- llama_target_and_test(test-arg-parser.cpp)
+ llama_build_and_test(test-arg-parser.cpp)
-# llama_target_and_test(test-opt.cpp) # SLOW
-llama_target_and_test(test-gguf.cpp)
-llama_target_and_test(test-backend-ops.cpp)
+# llama_build_and_test(test-opt.cpp) # SLOW
+llama_build_and_test(test-gguf.cpp)
+llama_build_and_test(test-backend-ops.cpp)
-llama_target_and_test(test-model-load-cancel.cpp LABEL "model")
-llama_target_and_test(test-autorelease.cpp LABEL "model")
if (NOT GGML_BACKEND_DL)
# these tests use the backends directly and cannot be built with dynamic loading
- llama_target_and_test(test-barrier.cpp)
- llama_target_and_test(test-quantize-fns.cpp)
- llama_target_and_test(test-quantize-perf.cpp)
- llama_target_and_test(test-rope.cpp)
+ llama_build_and_test(test-barrier.cpp)
+ llama_build_and_test(test-quantize-fns.cpp)
+ llama_build_and_test(test-rope.cpp)
diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp
index a0bf6affe5220..fa7aed82dfaa8 100644
--- a/tests/test-chat.cpp
+++ b/tests/test-chat.cpp
@@ -11,8 +11,9 @@
#include "chat.h"
using json = nlohmann::ordered_json;
diff --git a/examples/gbnf-validator/gbnf-validator.cpp b/tests/test-gbnf-validator.cpp
similarity index 98%
rename from examples/gbnf-validator/gbnf-validator.cpp
rename to tests/test-gbnf-validator.cpp
index a610e6a0b19d7..6547eec32fab4 100644
--- a/examples/gbnf-validator/gbnf-validator.cpp
+++ b/tests/test-gbnf-validator.cpp
@@ -1,5 +1,5 @@
#include <cstdlib>
diff --git a/tests/test-grammar-integration.cpp b/tests/test-grammar-integration.cpp
index 89060864894a4..8988c347e3e32 100644
--- a/tests/test-grammar-integration.cpp
+++ b/tests/test-grammar-integration.cpp
@@ -2,10 +2,11 @@
#undef NDEBUG
#include <vector>
diff --git a/tests/test-grammar-llguidance.cpp b/tests/test-grammar-llguidance.cpp
index 3c19220e11964..566b039a07038 100644
--- a/tests/test-grammar-llguidance.cpp
+++ b/tests/test-grammar-llguidance.cpp
@@ -2,7 +2,6 @@
# undef NDEBUG
#include "sampling.h"
@@ -84,7 +83,7 @@ static void test(const std::string & test_desc, const std::string & grammar_str,
fprintf(stderr,
"\n NOTE: Debug grammar file generated. To analyze this failure in detail, run the following "
- "command: ./llama-gbnf-validator test-grammar-integration.grammar.gbnf "
+ "command: ./test-gbnf-validator test-grammar-integration.grammar.gbnf "
"test-grammar-integration.string.txt\n\n");
} else {
fprintf(stdout, "✅︎\n");
diff --git a/tests/test-grammar-parser.cpp b/tests/test-grammar-parser.cpp
index 259172d999c78..67821a2d5c609 100644
--- a/tests/test-grammar-parser.cpp
+++ b/tests/test-grammar-parser.cpp
@@ -3,7 +3,9 @@
+// TODO: shold not include libllama sources
diff --git a/tests/test-json-schema-to-grammar.cpp b/tests/test-json-schema-to-grammar.cpp
index 4d78e914269f3..e35134f3cb063 100755
--- a/tests/test-json-schema-to-grammar.cpp
+++ b/tests/test-json-schema-to-grammar.cpp
@@ -4,7 +4,7 @@
#include <fstream>
diff --git a/tests/test-llama-grammar.cpp b/tests/test-llama-grammar.cpp
index e2129206be156..cc198f3e3c903 100644
--- a/tests/test-llama-grammar.cpp
+++ b/tests/test-llama-grammar.cpp
@@ -3,7 +3,8 @@
#include <stdexcept>
diff --git a/examples/quantize-stats/quantize-stats.cpp b/tests/test-quantize-stats.cpp
similarity index 99%
rename from examples/quantize-stats/quantize-stats.cpp
rename to tests/test-quantize-stats.cpp
index dd07ab9b37456..db01059119e9b 100644
--- a/examples/quantize-stats/quantize-stats.cpp
+++ b/tests/test-quantize-stats.cpp
#include "ggml.h"
+#include "../src/llama-model.h"
#include <algorithm>
#include <cinttypes>
diff --git a/tests/test-tokenizer-1-bpe.cpp b/tests/test-tokenizer-1-bpe.cpp
index 55425d88a7e07..b183da47f3cc8 100644
--- a/tests/test-tokenizer-1-bpe.cpp
+++ b/tests/test-tokenizer-1-bpe.cpp
diff --git a/tests/test-tokenizer-1-spm.cpp b/tests/test-tokenizer-1-spm.cpp
index 9e7b77f31ea12..ba6e94ba8ea57 100644
--- a/tests/test-tokenizer-1-spm.cpp
+++ b/tests/test-tokenizer-1-spm.cpp | [
"- add_subdirectory(gbnf-validator)",
"- endif()",
"-add_executable(${TARGET} gbnf-validator.cpp)",
"-target_include_directories(llama PUBLIC . ../include)",
"+ if (DEFINED LLAMA_TEST_NAME)",
"+ llama_build(test-quantize-stats.cpp)",
"+llama_build_and_test(test-model-load-cancel.cpp LABEL \"model\")",
"+llama_build_and_test(test-autorelease.cpp LABEL \"model\")",
"+ llama_build_and_test(test-quantize-perf.cpp)",
"-#include \"llama-model.h\""
] | [
30,
31,
54,
91,
107,
176,
223,
224,
234,
361
] | {
"additions": 64,
"author": "ggerganov",
"deletions": 69,
"html_url": "https://github.com/ggml-org/llama.cpp/pull/13062",
"issue_id": 13062,
"merged_at": "2025-04-24T13:00:10Z",
"omission_probability": 0.1,
"pr_number": 13062,
"repo": "ggml-org/llama.cpp",
"title": "cmake : do not include ./src as public for libllama",
"total_changes": 133
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.