[PATCH v2] tools/mm: prevent page_owner_sort from truncating input

From: Warren Xiong

Date: Wed Jul 29 2026 - 22:01:19 EST


page_owner_sort opens the output file with "w" before reading the input.
If both paths refer to the same file, this truncates the input and the
tool silently processes zero records before returning success.

Delay opening the output file until all input records have been loaded
into memory. This allows the tool to sort a file in place without
truncating data before it has been consumed.

Signed-off-by: Warren Xiong <warren.xiong@xxxxxxxxxx>
---
Changes in v2:
- Delay opening the output file until after all input has been loaded, as
suggested by Andrew Morton.
- Allow in-place sorting instead of rejecting matching input and output
files.

Tested with distinct paths, the same path, a hard-link alias, and a
symbolic-link alias.

Link to v1: https://lore.kernel.org/r/20260729053812.882137-1-warren.xiong@xxxxxxxxxx

tools/mm/page_owner_sort.c | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/tools/mm/page_owner_sort.c b/tools/mm/page_owner_sort.c
index 35d3d2549..22b3b500d 100644
--- a/tools/mm/page_owner_sort.c
+++ b/tools/mm/page_owner_sort.c
@@ -836,8 +836,7 @@ int main(int argc, char **argv)
}

fin = fopen(argv[optind], "r");
- fout = fopen(argv[optind + 1], "w");
- if (!fin || !fout) {
+ if (!fin) {
usage();
perror("open: ");
exit(1);
@@ -874,6 +873,13 @@ int main(int argc, char **argv)
goto out_free;
}

+ fout = fopen(argv[optind + 1], "w");
+ if (!fout) {
+ usage();
+ perror("open: ");
+ exit(1);
+ }
+
printf("loaded %d\n", list_size);

printf("sorting ....\n");
--
2.39.5