防止strcpy/strncpy内存溢出的my_strncpy

发布时间 2023-10-09 09:34:40作者: xingzhi_liu

my_strncpy:

1 char *my_strncpy(char *dest, const char *src, size_t size)
2 {
3     if (size <= 0)
4         return dest;
5 
6     dest[--size] = '\0';
7 
8     return strncpy(dest, src, size);
9 }

替换工程中的strcpy/strncpy为my_strncpy的python脚本,直接在根目录运行即可

my_strncpy_replace.py

 1 import os
 2 import re
 3 
 4 # 定义要进行替换的字符串 strcpy
 5 old_strcpy = "strcpy"
 6 
 7 # 定义要进行替换的字符串 strncpy
 8 old_strncpy = "strncpy"
 9 
10 # 定义要替换成的字符串
11 new_my_strncpy = "my_strncpy"
12 
13 # 获取当前目录的路径
14 current_directory = os.getcwd()
15 
16 # 定义替换函数 strcpy
17 def replace_strcpy(file_path, old_strcpy, new_my_strncpy):
18     # 打开文件进行读写
19     with open(file_path, "r+", encoding='utf-8') as f:
20         # 读取文件内容
21         contents = f.read()
22 
23         # 使用正则表达式查找包含旧函数调用的行,并将其替换为新函数调用
24         new_contents = re.sub(rf'{old_strcpy}\((.+?),\s*(.+?)\);', rf'{new_my_strncpy}(\1, \2, sizeof(\1));', contents)
25 
26         # 将文件指针移到文件开头
27         f.seek(0)
28 
29         # 将新内容写入文件
30         f.write(new_contents)
31 
32         # 截断文件
33         f.truncate()
34 
35 # 定义替换函数 strncpy
36 def replace_strncpy(file_path, old_strncpy, new_my_strncpy):
37     # 打开文件进行读写
38     with open(file_path, "r+", encoding='utf-8') as f:
39         # 读取文件内容
40         contents = f.read()
41 
42         # 使用正则表达式查找包含旧函数调用的行,并将其替换为新函数调用
43         new_contents = re.sub(rf'{old_strncpy}\((.+?),\s*(.+?),\s*(.+?)\);', rf'{new_my_strncpy}(\1, \2, sizeof(\1));', contents)
44 
45         # 将文件指针移到文件开头
46         f.seek(0)
47 
48         # 将新内容写入文件
49         f.write(new_contents)
50 
51         # 截断文件
52         f.truncate()
53 
54 # 遍历当前目录及其子目录下的所有文件 替换 strcpy
55 for root, dirs, files in os.walk(current_directory):
56     for file in files:
57         # 如果文件扩展名为 .c,则执行替换操作
58         if file.endswith(".c"):
59             file_path = os.path.join(root, file)
60             replace_strcpy(file_path, old_strcpy, new_my_strncpy)
61 
62 # 遍历当前目录及其子目录下的所有文件 替换 strncpy
63 for root, dirs, files in os.walk(current_directory):
64     for file in files:
65         # 如果文件扩展名为 .c,则执行替换操作
66         if file.endswith(".c"):
67             file_path = os.path.join(root, file)
68             replace_strncpy(file_path, old_strncpy, new_my_strncpy)
69 
70 # 遍历当前目录及其子目录中的所有.c文件
71 for root, dirs, files in os.walk(current_directory):
72     for file in files:
73         if file.endswith('.c'):
74             file_path = os.path.join(root, file)
75             # 读取文件内容
76             with open(file_path, 'r', encoding='utf-8') as f:
77                 file_contents = f.read()
78             
79             # 替换 "my_my_strncpy" 为 "my_strncpy"
80             modified_contents = file_contents.replace("my_my_strncpy", "my_strncpy")
81             
82             # 将修改后的内容写回文件
83             with open(file_path, 'w', encoding='utf-8') as f:
84                 f.write(modified_contents)
85 
86 print("Replace completed!")