aboutsummaryrefslogtreecommitdiff
path: root/src/zenutil/invocationhistory.cpp
blob: 49fdff31d2e5bf808e710174496e02846210d437 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zenutil/invocationhistory.h>

#include <zencore/basicfile.h>
#include <zencore/compactbinary.h>
#include <zencore/filesystem.h>
#include <zencore/iobuffer.h>
#include <zencore/memoryview.h>
#include <zencore/process.h>
#include <zencore/uid.h>

ZEN_THIRD_PARTY_INCLUDES_START
#include <json11.hpp>
ZEN_THIRD_PARTY_INCLUDES_END

#include <cstring>
#include <system_error>

namespace zen {

namespace {

	constexpr size_t		   kMaxRecords		= 100;
	constexpr std::string_view kHistoryFileName = "invocations.jsonl";

	// Safety cap. With 100 records at typical ~500-1000 bytes each the file
	// normally sits around 50-100 KB. If it has grown past this threshold
	// (external corruption, runaway producer, another tool writing garbage)
	// we refuse to read it and start fresh with just the new record. Keeps
	// LogInvocation from slowing startup on a pathological file.
	constexpr uintmax_t kMaxReadSize = 1 * 1024 * 1024;	 // 1 MB

	bool ExecutionHistoryDisabled(int argc, char** argv)
	{
		for (int I = 1; I < argc; ++I)
		{
			if (argv[I] == nullptr)
			{
				continue;
			}
			std::string_view A = argv[I];
			if (A == "--enable-execution-history=false" || A == "--enable-execution-history=0" || A == "--enable-execution-history=no")
			{
				return true;
			}
		}
		return false;
	}

	std::filesystem::path ResolveHistoryDir()
	{
#if ZEN_PLATFORM_WINDOWS
		std::string LocalAppData = GetEnvVariable("LOCALAPPDATA");
		if (!LocalAppData.empty())
		{
			return std::filesystem::path(LocalAppData) / "Epic" / "Zen" / "History";
		}
#endif
		std::filesystem::path SystemRoot = PickDefaultSystemRootDirectory();
		if (SystemRoot.empty())
		{
			return {};
		}
		return SystemRoot / "History";
	}

	std::string BuildJsonRecord(const HistoryRecord& Rec)
	{
		json11::Json::object Obj{
			{"id", Rec.Id},
			{"ts", Rec.Ts},
			{"exe", Rec.Exe},
			{"pid", static_cast<int>(Rec.Pid)},
			{"cwd", Rec.Cwd},
			{"path", Rec.Path},
			{"cmdline", Rec.CmdLine},
		};
		if (!Rec.Mode.empty())
		{
			Obj.emplace("mode", Rec.Mode);
		}
		return json11::Json(Obj).dump();
	}

	bool ParseJsonRecord(std::string_view Line, HistoryRecord& OutRec)
	{
		std::string	 Err;
		json11::Json J = json11::Json::parse(std::string(Line), Err);
		if (!Err.empty() || !J.is_object())
		{
			return false;
		}
		OutRec.Id	   = J["id"].string_value();
		OutRec.Ts	   = J["ts"].string_value();
		OutRec.Exe	   = J["exe"].string_value();
		OutRec.Mode	   = J["mode"].string_value();
		OutRec.Cwd	   = J["cwd"].string_value();
		OutRec.Path	   = J["path"].string_value();
		OutRec.CmdLine = J["cmdline"].string_value();
		OutRec.Pid	   = static_cast<uint32_t>(J["pid"].int_value());
		return true;
	}

	std::vector<std::string> ReadHistoryLines(const std::filesystem::path& Path)
	{
		std::vector<std::string> Lines;

		std::error_code		 SizeEc;
		const std::uintmax_t FileSize = std::filesystem::file_size(Path, SizeEc);
		if (SizeEc || FileSize > kMaxReadSize)
		{
			return Lines;
		}

		FileContents Contents = ReadFile(Path);
		if (!Contents)
		{
			return Lines;
		}
		IoBuffer	 Flat  = Contents.Flatten();
		const char*	 Data  = static_cast<const char*>(Flat.GetData());
		const size_t Size  = Flat.GetSize();
		size_t		 Start = 0;
		for (size_t I = 0; I < Size; ++I)
		{
			if (Data[I] == '\n')
			{
				if (I > Start)
				{
					size_t LineEnd = I;
					if (LineEnd > Start && Data[LineEnd - 1] == '\r')
					{
						--LineEnd;
					}
					if (LineEnd > Start)
					{
						Lines.emplace_back(Data + Start, LineEnd - Start);
					}
				}
				Start = I + 1;
			}
		}
		if (Start < Size)
		{
			Lines.emplace_back(Data + Start, Size - Start);
		}
		return Lines;
	}

}  // namespace

std::filesystem::path
GetInvocationHistoryPath() noexcept
{
	try
	{
		std::filesystem::path Dir = ResolveHistoryDir();
		if (Dir.empty())
		{
			return {};
		}
		return Dir / kHistoryFileName;
	}
	catch (...)
	{
		return {};
	}
}

void
LogInvocation(std::string_view						  Exe,
			  std::string_view						  Mode,
			  int									  argc,
			  char**								  argv,
			  std::initializer_list<std::string_view> ExcludeSubcommands) noexcept
{
	try
	{
		if (ExecutionHistoryDisabled(argc, argv))
		{
			return;
		}

		if (argc >= 2 && argv[1] != nullptr)
		{
			std::string_view A1 = argv[1];
			for (std::string_view Excluded : ExcludeSubcommands)
			{
				if (A1 == Excluded)
				{
					return;
				}
			}
		}

		std::filesystem::path Dir = ResolveHistoryDir();
		if (Dir.empty())
		{
			return;
		}

		std::error_code Ec;
		CreateDirectories(Dir, Ec);
		if (Ec)
		{
			return;
		}

		std::filesystem::path Path = Dir / kHistoryFileName;

		HistoryRecord Rec;
		Rec.Id	 = Oid::NewOid().ToString();
		Rec.Ts	 = DateTime::Now().ToIso8601();
		Rec.Exe	 = std::string(Exe);
		Rec.Mode = std::string(Mode);

		std::error_code CwdEc;
		Rec.Cwd = std::filesystem::current_path(CwdEc).string();

		Rec.Path = GetRunningExecutablePath().string();
		Rec.Pid	 = static_cast<uint32_t>(GetCurrentProcessId());

		std::string Raw = GetRawCommandLine();
		if (!Raw.empty())
		{
			Rec.CmdLine = std::move(Raw);
		}
		else
		{
			std::vector<std::string> Args;
			Args.reserve(argc);
			for (int I = 0; I < argc; ++I)
			{
				if (argv[I] != nullptr)
				{
					Args.emplace_back(argv[I]);
				}
			}
			Rec.CmdLine = BuildCommandLine(Args);
		}

		std::vector<std::string> Lines = ReadHistoryLines(Path);
		if (Lines.size() >= kMaxRecords)
		{
			Lines.erase(Lines.begin(), Lines.begin() + (Lines.size() - (kMaxRecords - 1)));
		}
		Lines.push_back(BuildJsonRecord(Rec));

		std::string NewContents;
		size_t		TotalSize = 0;
		for (const std::string& L : Lines)
		{
			TotalSize += L.size() + 1;
		}
		NewContents.reserve(TotalSize);
		for (const std::string& L : Lines)
		{
			NewContents.append(L);
			NewContents.push_back('\n');
		}

		std::error_code WriteEc;
		TemporaryFile::SafeWriteFile(Path, MemoryView(NewContents.data(), NewContents.size()), WriteEc);
	}
	catch (...)
	{
	}
}

std::vector<HistoryRecord>
ReadInvocationHistory(size_t MaxRecords)
{
	std::vector<HistoryRecord> Records;
	try
	{
		std::filesystem::path Path = GetInvocationHistoryPath();
		if (Path.empty())
		{
			return Records;
		}

		std::vector<std::string> Lines = ReadHistoryLines(Path);
		if (Lines.size() > MaxRecords)
		{
			Lines.erase(Lines.begin(), Lines.begin() + (Lines.size() - MaxRecords));
		}

		Records.reserve(Lines.size());
		for (const std::string& L : Lines)
		{
			HistoryRecord Rec;
			if (ParseJsonRecord(L, Rec))
			{
				Records.push_back(std::move(Rec));
			}
		}
	}
	catch (...)
	{
	}
	return Records;
}

void
invocationhistory_forcelink()
{
}

}  // namespace zen