Repository navigation
Expand file tree
/
Copy pathProcess.cpp
More file actions
323 lines (261 loc) · 8.91 KB
/
Copy pathProcess.cpp
File metadata and controls
323 lines (261 loc) · 8.91 KB
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
311
312
313
314
315
316
317
318
319
320
321
322
323
#include "Process.h"
#include <filesystem>
#include <iostream>
#include <limits>
#include "Config.h"
#include "Utils.h"
Process::Process(int pid, const std::string& name, size_t memorySize)
: pid(pid),
name(name),
createdAt(currentTimestamp()),
commandCounter(0),
coreId(-1),
currentState(READY),
sleepTicks(0),
fileOpened(false),
screenSessionExists(false),
screenAttached(false),
processMemory(std::max<size_t>(memorySize, ProcessMemory::SYMBOL_TABLE_BYTES)) {}
void Process::addCommand(std::shared_ptr<ICommand> command) {
commandList.push_back(std::move(command));
}
void Process::executeCurrentCommand(int coreId) {
if (isFinished()) {
return;
}
int index = commandCounter.load();
if (index < 0 || index >= static_cast<int>(commandList.size())) {
return;
}
// "Page fault handling continuously occurs until a valid page has been
// returned, before an instruction is performed." The pager services the
// fault during the failed attempt, so retrying here lets the instruction
// complete in the same tick instead of costing a full cycle per fault --
// which otherwise starves processes under heavy thrashing. The attempt
// count is bounded so a page that can never be made resident yields the
// core rather than spinning.
constexpr int maxFaultRetries = 8;
bool completed = false;
for (int attempt = 0; attempt < maxFaultRetries && !completed; ++attempt) {
completed = commandList[index]->execute(coreId, *this);
if (isTerminated()) return; // access violation shut the process down
}
if (completed) {
commandCounter.fetch_add(1);
}
}
void Process::finishExecution() {
if (isTerminated()) {
if (fileOpened) {
outFile.close();
fileOpened = false;
}
return;
}
currentState.store(FINISHED);
{
std::lock_guard<std::mutex> lock(screenMutex);
screenLogs.push_back("Finished!");
}
if (fileOpened) {
outFile.close();
fileOpened = false;
}
}
bool Process::isFinished() const {
if (memoryViolation.load()) return true;
return commandCounter.load() >= static_cast<int>(commandList.size());
}
void Process::logPrint(int coreId, const std::string& message) {
std::string timestamp = currentTimestamp();
std::string entry = "(" + timestamp + ") Core:" + std::to_string(coreId) + " \"" + message + "\"";
{
std::lock_guard<std::mutex> lock(screenMutex);
screenLogs.push_back(entry);
}
if (!Config::WRITE_PRINT_FILES) {
return;
}
if (!fileOpened) {
std::filesystem::create_directories("process_logs");
std::string path = "process_logs/" + name + ".txt";
outFile.open(path);
outFile << "Process name: " << name << "\n";
outFile << "Logs:\n\n";
fileOpened = true;
}
outFile << "(" << currentTimestamp() << ") Core:" << coreId
<< " \"" << message << "\"\n";
}
void Process::setState(ProcessState state) {
currentState.store(state);
}
void Process::setCoreId(int coreId) {
this->coreId.store(coreId);
}
// --- Variables ------------------------------------------------------------
bool Process::resolveVariableAddress(const std::string& name, size_t& outAddress, bool allowCreate) {
if (allowCreate) {
return symbolTable.addressOf(name, outAddress);
}
return symbolTable.find(name, outAddress);
}
MemoryStatus Process::declareVariable(const std::string& name, uint16_t value) {
size_t address = 0;
if (!resolveVariableAddress(name, address, true)) {
// 32-variable limit reached: the spec says to ignore the declaration.
return MemoryStatus::IGNORED;
}
return writeMemory(address, value);
}
MemoryStatus Process::readVariable(const std::string& name, uint16_t& outValue) {
size_t address = 0;
if (!resolveVariableAddress(name, address, true)) {
// Undeclared and no slot left: reads fall back to 0 rather than failing.
outValue = 0;
return MemoryStatus::OK;
}
return readMemory(address, outValue);
}
MemoryStatus Process::writeVariable(const std::string& name, uint32_t value) {
size_t address = 0;
if (!resolveVariableAddress(name, address, true)) {
return MemoryStatus::IGNORED;
}
// uint16 values are clamped to [0, 65535].
uint32_t clamped = std::min<uint32_t>(value, std::numeric_limits<uint16_t>::max());
return writeMemory(address, static_cast<uint16_t>(clamped));
}
// --- Raw memory -----------------------------------------------------------
// These two functions are the seam for demand paging. Both pages a uint16 can
// span are known here, so making them resident (and returning PAGE_FAULT so the
// instruction restarts) is a local change -- no command needs to be touched.
void Process::setPageAccessHandler(PageAccessHandler handler) {
pageAccessHandler = std::move(handler);
}
MemoryStatus Process::readMemory(size_t address, uint16_t& outValue) {
if (!processMemory.isValidWordAddress(address)) {
raiseAccessViolation(address);
return MemoryStatus::VIOLATION;
}
// --- DEMAND PAGING SEAM ---
// Check if the page is resident. If not, fault!
if (pageAccessHandler && !pageAccessHandler(address)) {
return MemoryStatus::PAGE_FAULT;
}
outValue = processMemory.readWord(address);
return MemoryStatus::OK;
}
MemoryStatus Process::writeMemory(size_t address, uint16_t value) {
if (!processMemory.isValidWordAddress(address)) {
raiseAccessViolation(address);
return MemoryStatus::VIOLATION;
}
// --- DEMAND PAGING SEAM ---
// Check if the page is resident. If not, fault!
if (pageAccessHandler && !pageAccessHandler(address)) {
return MemoryStatus::PAGE_FAULT;
}
processMemory.writeWord(address, value);
return MemoryStatus::OK;
}
// --- Scheduling state -----------------------------------------------------
bool Process::isSleeping() const {
return sleepTicks.load() > 0;
}
int Process::getSleepTicks() const {
return sleepTicks.load();
}
void Process::sleepFor(int ticks) {
sleepTicks.store(ticks);
}
bool Process::tickSleep() {
int remaining = sleepTicks.load();
if (remaining <= 0) {
return true;
}
remaining = std::max(0, remaining - 1);
sleepTicks.store(remaining);
return remaining == 0;
}
int Process::getPID() const {
return pid;
}
std::string Process::getName() const {
return name;
}
std::string Process::getCreatedAt() const {
return createdAt;
}
Process::ProcessState Process::getState() const {
return currentState.load();
}
int Process::getCoreId() const {
return coreId.load();
}
int Process::getCurrentLine() const {
return commandCounter.load();
}
int Process::getTotalLines() const {
return static_cast<int>(commandList.size());
}
void Process::attachScreen() {
std::lock_guard<std::mutex> lock(screenMutex);
screenSessionExists = true;
screenAttached = true;
}
void Process::detachScreen() {
std::lock_guard<std::mutex> lock(screenMutex);
screenAttached = false;
}
bool Process::hasScreenSession() const {
std::lock_guard<std::mutex> lock(screenMutex);
return screenSessionExists;
}
bool Process::isScreenAttached() const {
std::lock_guard<std::mutex> lock(screenMutex);
return screenAttached;
}
std::vector<std::string> Process::getScreenLogs() const {
std::lock_guard<std::mutex> lock(screenMutex);
return screenLogs;
}
bool Process::isBusyWaiting(uint64_t currentGlobalClock) const {
return currentGlobalClock < busyWaitDeadline.load();
}
void Process::startBusyWait(uint64_t currentGlobalClock, int delayCycles) {
busyWaitDeadline.store(currentGlobalClock + static_cast<uint64_t>(delayCycles));
}
size_t Process::getMemorySize() const {
return processMemory.getSize();
}
ProcessMemory& Process::memory() {
return processMemory;
}
// --- Access violation -----------------------------------------------------
void Process::raiseAccessViolation(size_t address) {
{
std::lock_guard<std::mutex> lock(violationMutex);
if (memoryViolation.load()) return; // keep the first violation
violationTime = currentTimeOfDay();
invalidAddress = toHexAddress(address);
}
currentState.store(TERMINATED);
memoryViolation.store(true); // set last, after the strings are written
logPrint(coreId.load(),
"ACCESS VIOLATION at " + toHexAddress(address) + " - process shut down");
}
bool Process::hasMemoryViolation() const {
return memoryViolation.load();
}
bool Process::isTerminated() const {
return memoryViolation.load();
}
std::string Process::getViolationTime() const {
std::lock_guard<std::mutex> lock(violationMutex);
return violationTime;
}
std::string Process::getInvalidAddress() const {
std::lock_guard<std::mutex> lock(violationMutex);
return invalidAddress;
}