plcopen 0.22.0
载入中...
搜索中...
未找到
vm.h
浏览该文件的文档.
1#pragma once
2
3// RT-SAFE: ST bytecode interpreter (approved st-l0-semantics 3.1-3.7).
4// scan() is cycle-path code: zero allocation, no exceptions, bounded by an
5// instruction-count budget (deterministic watchdog, matrix 3.6). All memory
6// lives in the caller-provided buffer laid out at load (matrix 3.2). Fault
7// semantics per matrix 3.7: the scan stops at the faulting instruction,
8// prior assignments stay, the fault latches until reset().
9
10#include <algorithm>
11#include <array>
12#include <cmath>
13#include <cstdint>
14#include <cstring>
15#include <limits>
16#include <new>
17
18#include "rt/error.h"
19#include "st/binding.h"
20#include "st/binding_storage.h"
21#include "st/bind.h"
22#include "st/bytecode.h"
23#include "st/process_image.h"
24#include "st/types.h"
25
26namespace plcopen::core::axis
27{
28class AxisModel;
29class AxisGroup;
30}
31
32namespace plcopen::core::st
33{
34
35enum class ScanError : std::uint8_t
36{
37 ok = 0,
43 conversion_invalid, // NaN/Inf into an integer domain (L1a 4.3/5.1)
44 range_violation, // enum/subrange/string/index validation (L1b+)
50};
51
52constexpr const char *to_string(ScanError error)
53{
54 switch(error) {
55 case ScanError::ok: return "ok";
56 case ScanError::not_loaded: return "not_loaded";
57 case ScanError::division_by_zero: return "division_by_zero";
58 case ScanError::for_step_zero: return "for_step_zero";
59 case ScanError::budget_exceeded: return "budget_exceeded";
60 case ScanError::invalid_bytecode: return "invalid_bytecode";
61 case ScanError::conversion_invalid: return "conversion_invalid";
62 case ScanError::range_violation: return "range_violation";
63 case ScanError::string_capacity_exceeded: return "string_capacity_exceeded";
64 case ScanError::date_time_range_violation: return "date_time_range_violation";
65 case ScanError::alias_violation: return "alias_violation";
66 case ScanError::invalid_argument: return "invalid_argument";
67 case ScanError::paused: return "paused";
68 }
69 return "unknown";
70}
71
72enum class InstanceState : std::uint8_t
73{
74 idle = 0,
78};
79
81{
82public:
83 Instance() = default;
84 Instance(const Instance &) = delete;
85 Instance &operator=(const Instance &) = delete;
86 Instance(Instance &&) = delete;
88
90
91 rt::ErrorCode inject_utc_dt(std::int64_t value) noexcept
92 {
93 utc_dt_ns_ = value;
94 return rt::ErrorCode::ok;
95 }
96 std::int64_t utc_dt_ns() const noexcept { return utc_dt_ns_; }
97
98 void unload() noexcept
99 {
100 if(program_ != nullptr && fb_area_ != nullptr) {
101 for(const FbInfo &fb : program_->fbs) {
102 fb_destroy(fb.type, fb_area_ + fb.offset);
103 }
104 }
105 program_ = nullptr;
106 process_image_ = nullptr;
107 vars_ = nullptr;
108 visible_vars_ = nullptr;
109 execution_vars_ = nullptr;
110 sfc_runtime_ = nullptr;
111 sfc_runner_ = nullptr;
112 fb_area_ = nullptr;
113 stack_ = nullptr;
114 fault_ = ScanError::ok;
115 execution_state_ = InstanceState::idle;
116 pc_ = 0;
117 instruction_pc_ = 0;
118 sp_ = 0;
119 remaining_budget_ = 0;
120 scan_started_ = false;
121 defer_process_image_publish_ = false;
122 axis_targets_ = nullptr;
123 group_targets_ = nullptr;
124 path_tables_ = nullptr;
125 path_descriptions_ = nullptr;
126 cam_switch_tables_ = nullptr;
127 cam_switch_outputs_ = nullptr;
128 cam_track_options_ = nullptr;
129 cam_tables_ = nullptr;
130 position_profiles_ = nullptr;
131 velocity_profiles_ = nullptr;
132 acceleration_profiles_ = nullptr;
133 kin_transforms_ = nullptr;
134 task_period_ns_ = 0;
135 debug_hooks_ = nullptr;
136 }
137
138 // Load domain. The program object must outlive the instance; the buffer
139 // is caller-owned static storage, 8-byte aligned, at least
140 // program.required_bytes() long.
141 rt::ErrorCode load(const Program &program, unsigned char *buffer,
142 std::size_t buffer_bytes, std::int64_t task_period_ns)
143 {
144 unload();
145 if(program.format_version != kBytecodeFormatVersion) {
147 }
148 if(buffer == nullptr || task_period_ns <= 0) {
150 }
151 if((reinterpret_cast<std::uintptr_t>(buffer) & 7U) != 0) {
153 }
154 if(buffer_bytes < program.required_bytes()) {
156 }
157 vars_ = buffer;
158 visible_vars_ = vars_;
159 execution_vars_ = vars_;
160 fb_area_ = buffer + program.vars_bytes;
161 stack_ = reinterpret_cast<std::uint64_t *>(fb_area_ + program.fb_bytes);
162 std::memset(buffer, 0, program.required_bytes());
163 unsigned char *binding_storage =
164 buffer + program.binding_storage_offset();
165 load_binding_storage(program, binding_storage);
166 sfc_runner_ = ::new(static_cast<void *>(
167 buffer + program.sfc_runner_storage_offset())) SfcRunnerStorage{};
168 sfc_runtime_ = buffer + program.sfc_storage_offset();
169 if(program.needs_debug_runtime_storage()) {
170 ::new(static_cast<void *>(
171 buffer + program.debug_runtime_storage_offset()))
173 }
174 if(program.initial_data.size() > program.vars_bytes) {
176 }
177 if(!program.initial_data.empty()) {
178 std::memcpy(vars_, program.initial_data.data(),
179 program.initial_data.size());
180 }
181 for(const VarInfo &var : program.vars) {
182 const TypeDesc *desc = program.types.get(var.type_id);
183 if(desc == nullptr ||
184 (desc->kind != TypeKind::string &&
185 desc->kind != TypeKind::wstring)) {
186 continue;
187 }
188 if(var.offset > program.vars_bytes ||
189 desc->size > program.vars_bytes - var.offset ||
190 !valid_string_object(vars_ + var.offset, *desc)) {
192 }
193 }
194 for(const FbInfo &fb : program.fbs) {
195 fb_init(fb.type, fb_area_ + fb.offset, task_period_ns);
196 }
197 task_period_ns_ = task_period_ns;
198 program_ = &program;
199 initialize_sfc_runtime();
200 fault_ = ScanError::ok;
201 execution_state_ = InstanceState::idle;
202 pc_ = 0;
203 instruction_pc_ = 0;
204 sp_ = 0;
205 remaining_budget_ = 0;
206 scan_started_ = false;
207 return rt::ErrorCode::ok;
208 }
209
210 rt::ErrorCode load(const Program &program, unsigned char *buffer,
211 std::size_t buffer_bytes, std::int64_t task_period_ns,
212 ProcessImage *process_image)
213 {
214 if(process_image == nullptr || !process_image->supports(program)) {
216 }
217 const rt::ErrorCode loaded =
218 load(program, buffer, buffer_bytes, task_period_ns);
219 if(loaded == rt::ErrorCode::ok) process_image_ = process_image;
220 return loaded;
221 }
222
224 unsigned char *buffer, std::size_t buffer_bytes,
225 std::int64_t task_period_ns)
226 {
227 if(program_name == nullptr) {
229 }
230 const Program *selected = &program;
231 if(!program.programs.empty()) {
232 selected = nullptr;
233 for(const Program &candidate : program.programs) {
234 std::size_t i = 0;
235 while(i < candidate.program_name.size() &&
236 program_name[i] != '\0') {
237 char c = program_name[i];
238 if(c >= 'A' && c <= 'Z') {
239 c = static_cast<char>(c - 'A' + 'a');
240 }
241 if(c != candidate.program_name[i]) {
242 break;
243 }
244 ++i;
245 }
246 if(i == candidate.program_name.size() &&
247 program_name[i] == '\0') {
248 selected = &candidate;
249 break;
250 }
251 }
252 if(selected == nullptr) {
254 }
255 } else if(!program.program_name.empty()) {
256 std::size_t i = 0;
257 while(i < program.program_name.size() && program_name[i] != '\0') {
258 char c = program_name[i];
259 if(c >= 'A' && c <= 'Z') {
260 c = static_cast<char>(c - 'A' + 'a');
261 }
262 if(c != program.program_name[i]) {
264 }
265 ++i;
266 }
267 if(i != program.program_name.size() || program_name[i] != '\0') {
269 }
270 }
271 return load(*selected, buffer, buffer_bytes, task_period_ns);
272 }
273
275 {
277 }
278
280 {
282 }
283
284 BindingError bind_reference(const char *name, BindingTarget target)
285 {
286 if(program_ == nullptr || name == nullptr) {
288 }
289 if(scan_started_) {
291 }
292 std::uint16_t axis_slot = 0;
293 std::uint16_t group_slot = 0;
294 for(const VarInfo &var : program_->vars) {
295 const BindingTargetKind kind = reference_kind(var.type,
296 var.type_id);
297 if(kind == BindingTargetKind::invalid) {
298 continue;
299 }
300 const std::uint16_t slot = kind == BindingTargetKind::axis
301 ? axis_slot++
302 : group_slot++;
303 if(!ascii_name_equal(name, var.lower)) {
304 continue;
305 }
306 if(target.pointer() == nullptr) {
308 }
309 if(target.kind() != kind) {
311 }
312 if((kind == BindingTargetKind::axis &&
313 slot >= axis_targets_->size()) ||
314 (kind == BindingTargetKind::group &&
315 slot >= group_targets_->size())) {
317 }
318 std::uint64_t handle = 0;
319 std::memcpy(&handle, vars_ + var.offset, sizeof(handle));
320 if(handle != 0) {
322 }
323 if(kind == BindingTargetKind::axis) {
324 (*axis_targets_)[slot] =
325 static_cast<axis::AxisModel *>(target.pointer());
326 } else {
327 auto *group =
328 static_cast<axis::AxisGroup *>(target.pointer());
329 const rt::ErrorCode period_result =
330 group->set_task_cycle_period_ns(task_period_ns_);
331 if(period_result != rt::ErrorCode::ok &&
332 group->task_cycle_period_ns() != task_period_ns_) {
334 }
335 (*group_targets_)[slot] = group;
336 }
337 handle = static_cast<std::uint64_t>(slot) + 1U;
338 std::memcpy(vars_ + var.offset, &handle, sizeof(handle));
339 return BindingError::ok;
340 }
342 }
343
345 {
346 if(table == nullptr) return BindingError::null_target;
347 return bind_named_handle(
348 name, binding_type::mc_path_table, path_tables_->size(),
349 [&](std::size_t slot) {
350 (*path_tables_)[slot] = table;
351 return BindingError::ok;
352 });
353 }
354
356 const fb::PathWaypoint *waypoints,
357 std::size_t count)
358 {
359 if(waypoints == nullptr) return BindingError::null_target;
360 fb::PathDescription decoded{};
363 }
364 const std::size_t axis_count = waypoints[0].target.size;
365 if(axis_count < 2U || axis_count > axis::GroupPosition::MaxAxes) {
367 }
368 for(std::size_t index = 0; index < count; ++index) {
369 if(waypoints[index].target.size != axis_count ||
370 fb::validate_path_waypoint(waypoints[index], axis_count) !=
373 }
374 decoded.waypoints[index] = waypoints[index];
375 }
376 decoded.count = count;
377 return bind_named_handle(
379 path_descriptions_->size(), [&](std::size_t slot) {
380 (*path_descriptions_)[slot] = decoded;
381 return BindingError::ok;
382 });
383 }
384
386 axis::KinTransformRef transform)
387 {
388 switch(transform.kind) {
390 if(transform.kinematics == nullptr || transform.pose != nullptr) {
392 }
393 break;
395 if(transform.pose == nullptr || transform.kinematics != nullptr) {
397 }
398 break;
400 default:
401 // Handle 0 is the canonical none/clear value; the registry only
402 // owns concrete non-owning plugin references.
404 }
405 return bind_named_handle(
407 kin_transforms_->size(), [&](std::size_t slot) {
408 (*kin_transforms_)[slot] = transform;
409 return BindingError::ok;
410 });
411 }
412
414 const fb::CamSwitchAction *data,
415 std::size_t count)
416 {
417 if(data == nullptr) return BindingError::null_target;
419 for(std::size_t index = 0; index < count; ++index) {
420 const fb::CamSwitchAction &action = data[index];
421 if(action.track_number == 0U ||
423 !std::isfinite(action.on_position) ||
424 !std::isfinite(data[index].off_position) ||
425 !std::isfinite(action.period) || action.period < 0.0 ||
426 (action.axis_direction !=
428 action.axis_direction !=
430 action.axis_direction !=
432 (action.cam_switch_mode !=
434 action.cam_switch_mode != fb::CamSwitchAction::Mode::time) ||
435 (action.cam_switch_mode ==
437 action.period == 0.0 &&
438 action.on_position > action.off_position) ||
439 (action.cam_switch_mode == fb::CamSwitchAction::Mode::time &&
440 action.duration_ns <= 0)) {
442 }
443 }
444 return bind_named_handle(
446 cam_switch_tables_->size(), [&](std::size_t slot) {
447 (*cam_switch_tables_)[slot] = {data, count};
448 return BindingError::ok;
449 });
450 }
451
452 BindingError bind_cam_switch_outputs(const char *name, bool *data,
453 std::size_t count)
454 {
455 if(data == nullptr) return BindingError::null_target;
458 }
459 return bind_named_handle(
461 cam_switch_outputs_->size(), [&](std::size_t slot) {
462 (*cam_switch_outputs_)[slot] = {data, count};
463 return BindingError::ok;
464 });
465 }
466
468 const fb::CamTrackOption *data,
469 std::size_t count)
470 {
471 if(data == nullptr) return BindingError::null_target;
472 if(count < 1U || count > axis::AxisModel::DigitalOutputCount) {
474 }
475 return bind_named_handle(
477 cam_track_options_->size(), [&](std::size_t slot) {
478 (*cam_track_options_)[slot] = {data, count};
479 return BindingError::ok;
480 });
481 }
482
483 BindingError bind_cam_table(const char *name, const exec::CamPoint *data,
484 std::size_t count, bool periodic)
485 {
486 if(data == nullptr) return BindingError::null_target;
487 const exec::CamTableView view{data, count, periodic};
488 if(count > 64U || !view.valid()) return BindingError::invalid_value;
489 return bind_named_handle(
490 name, binding_type::mc_cam_table_view, cam_tables_->size(),
491 [&](std::size_t slot) {
492 (*cam_tables_)[slot] = view;
493 return BindingError::ok;
494 });
495 }
496
498 const char *name, const BindingPositionProfileEntry *entries,
499 std::size_t count)
500 {
501 BindingProfileSlot decoded{};
502 if(entries == nullptr) return BindingError::null_target;
503 if(count < 1U || count > decoded.segments.size()) {
505 }
506 for(std::size_t index = 0; index < count; ++index) {
507 std::int64_t cycles = 0;
508 if(entries[index].time_ns <= 0 ||
510 entries[index].time_ns, task_period_ns_, cycles) ||
511 !std::isfinite(entries[index].position) ||
512 !std::isfinite(entries[index].velocity) ||
513 !std::isfinite(entries[index].acceleration) ||
514 !std::isfinite(entries[index].deceleration) ||
515 !std::isfinite(entries[index].jerk)) {
517 }
518 axis::ProfileSegment &segment = decoded.segments[index];
519 segment.duration_cycles = cycles;
520 segment.target = entries[index].position;
521 segment.velocity = entries[index].velocity;
522 segment.acceleration = entries[index].acceleration;
523 segment.deceleration = entries[index].deceleration;
524 segment.jerk = entries[index].jerk;
525 segment.relative = entries[index].relative;
526 }
527 decoded.count = count;
528 return bind_profile(name, binding_type::mc_time_position,
529 *position_profiles_, decoded);
530 }
531
533 const char *name, const BindingVelocityProfileEntry *entries,
534 std::size_t count)
535 {
536 BindingProfileSlot decoded{};
537 if(entries == nullptr) return BindingError::null_target;
538 if(count < 1U || count > decoded.segments.size()) {
540 }
541 for(std::size_t index = 0; index < count; ++index) {
542 std::int64_t cycles = 0;
543 if(entries[index].time_ns <= 0 ||
545 entries[index].time_ns, task_period_ns_, cycles) ||
546 !std::isfinite(entries[index].velocity) ||
547 !std::isfinite(entries[index].acceleration) ||
548 !std::isfinite(entries[index].deceleration) ||
549 !std::isfinite(entries[index].jerk)) {
551 }
552 axis::ProfileSegment &segment = decoded.segments[index];
553 segment.duration_cycles = cycles;
554 segment.target = entries[index].velocity;
555 segment.acceleration = entries[index].acceleration;
556 segment.deceleration = entries[index].deceleration;
557 segment.jerk = entries[index].jerk;
558 }
559 decoded.count = count;
560 return bind_profile(name, binding_type::mc_time_velocity,
561 *velocity_profiles_, decoded);
562 }
563
565 const char *name, const BindingAccelerationProfileEntry *entries,
566 std::size_t count)
567 {
568 BindingProfileSlot decoded{};
569 if(entries == nullptr) return BindingError::null_target;
570 if(count < 1U || count > decoded.segments.size()) {
572 }
573 for(std::size_t index = 0; index < count; ++index) {
574 std::int64_t cycles = 0;
575 if(entries[index].time_ns <= 0 ||
577 entries[index].time_ns, task_period_ns_, cycles) ||
578 !std::isfinite(entries[index].acceleration)) {
580 }
581 decoded.segments[index].duration_cycles = cycles;
582 decoded.segments[index].target = entries[index].acceleration;
583 }
584 decoded.count = count;
585 return bind_profile(name, binding_type::mc_time_acceleration,
586 *acceleration_profiles_, decoded);
587 }
588
589 // Clears a latched fault; variable and FB state keep their values
590 // (declared in the implementation record). A fresh start is a reload.
591 void reset()
592 {
593 fault_ = ScanError::ok;
594 abort();
595 }
596
598 {
599 return fault_;
600 }
601
602 InstanceState execution_state() const noexcept { return execution_state_; }
603 bool running() const noexcept
604 {
605 return execution_state_ == InstanceState::running;
606 }
607 bool complete() const noexcept
608 {
609 return execution_state_ == InstanceState::complete;
610 }
611
612 void defer_process_image_publish(bool defer) noexcept
613 {
614 defer_process_image_publish_ = defer;
615 }
616 std::int64_t remaining_budget() const noexcept
617 {
618 return remaining_budget_;
619 }
620 std::uint32_t instruction_offset() const noexcept
621 {
622 return static_cast<std::uint32_t>(instruction_pc_);
623 }
624 const char *program_name() const noexcept
625 {
626 return program_ == nullptr ? "" : program_->program_name.c_str();
627 }
628
630 std::size_t mapping) noexcept
631 {
632 debug_hooks_ = hooks;
633 DebugRuntimeStorage *runtime = debug_runtime_storage();
634 if(hooks != nullptr && runtime != nullptr) {
635 runtime->mapping = static_cast<std::uint32_t>(mapping);
636 }
637 }
638
639 const Program *program() const noexcept { return program_; }
640
641 const SourceMapEntry *last_debug_entry() const noexcept
642 {
643 if(const DebugRuntimeStorage *runtime = debug_runtime_storage()) {
644 return runtime->last_entry;
645 }
646 return nullptr;
647 }
649 {
650 if(const DebugRuntimeStorage *runtime = debug_runtime_storage()) {
651 return runtime->last_instruction_id;
652 }
653 static const InstructionId empty{};
654 return empty;
655 }
656
657 bool read_variable(std::uint32_t offset, std::uint32_t size,
658 unsigned char *destination) const noexcept
659 {
660 if(destination == nullptr || visible_vars_ == nullptr ||
661 program_ == nullptr || offset > program_->vars_bytes ||
662 size > program_->vars_bytes - offset)
663 return false;
664 std::memcpy(destination, visible_vars_ + offset, size);
665 return true;
666 }
667
668 rt::ErrorCode sfc_step_active(const char *network_name,
669 const char *step_name,
670 bool &active) const noexcept
671 {
672 active = false;
673 if(program_ == nullptr || network_name == nullptr ||
674 step_name == nullptr || sfc_runtime_ == nullptr)
676 for(const SfcNetworkInfo &network : program_->sfc_networks) {
677 if(!ascii_name_equal(network_name, network.lower)) continue;
678 for(std::size_t index = 0; index < network.steps.size(); ++index) {
679 if(ascii_name_equal(step_name, network.steps[index].lower)) {
680 const std::uint32_t offset =
681 running() && sfc_runner_->phase != SfcRunnerPhase::stage_vars
682 ? network.shadow_active_offset
683 : network.committed_active_offset;
684 active = sfc_runtime_[offset + index] != 0;
685 return rt::ErrorCode::ok;
686 }
687 }
689 }
691 }
692
693 bool debug_sfc_committed_step_active(std::size_t network,
694 std::size_t step) const noexcept
695 {
696 if(program_ == nullptr || sfc_runtime_ == nullptr ||
697 network >= program_->sfc_networks.size() ||
698 step >= program_->sfc_networks[network].steps.size())
699 return false;
700 return sfc_runtime_[program_->sfc_networks[network]
701 .committed_active_offset + step] != 0;
702 }
703
705 std::size_t capacity) noexcept
706 {
707 if((records == nullptr) != (capacity == 0))
710 sfc_runner_->trace = records;
711 sfc_runner_->trace_capacity = capacity;
712 sfc_runner_->trace_size = 0;
713 sfc_runner_->trace_dropped = 0;
714 sfc_runner_->trace_scan_begin_size = 0;
715 sfc_runner_->trace_scan_begin_dropped = 0;
716 return rt::ErrorCode::ok;
717 }
718
719 std::size_t sfc_trace_size() const noexcept { return sfc_runner_->trace_size; }
720 std::uint64_t sfc_trace_dropped() const noexcept
721 {
722 return sfc_runner_->trace_dropped;
723 }
724
725 rt::ErrorCode restart_sfc(const char *network_name) noexcept
726 {
727 if(program_ == nullptr || network_name == nullptr || running())
729 for(const SfcNetworkInfo &network : program_->sfc_networks) {
730 if(!ascii_name_equal(network_name, network.lower)) continue;
731 reset_sfc_network(network);
732 return rt::ErrorCode::ok;
733 }
735 }
736
737 std::uint32_t fault_sfc_network_index() const noexcept
738 {
739 return sfc_runner_->fault_network_index;
740 }
741 std::uint32_t fault_sfc_element_index() const noexcept
742 {
743 return sfc_runner_->fault_element_index;
744 }
746 {
747 return sfc_runner_->fault_element_kind;
748 }
749
750 ScanError begin(std::int64_t budget)
751 {
752 if(program_ == nullptr) return ScanError::not_loaded;
753 if(fault_ != ScanError::ok) return fault_;
754 if(execution_state_ == InstanceState::running)
756 if(process_image_ != nullptr)
757 process_image_->begin_scan(*program_, vars_);
758 if(!program_->sfc_networks.empty()) {
759 execution_vars_ = sfc_runtime_;
760 } else {
761 execution_vars_ = vars_;
762 }
763 scan_started_ = true;
764 execution_state_ = InstanceState::running;
765 pc_ = 0;
766 instruction_pc_ = 0;
767 sp_ = 0;
768 remaining_budget_ = budget;
769 sfc_runner_->active_region = nullptr;
770 sfc_runner_->phase = program_->sfc_networks.empty()
772 : (program_->vars_bytes == 0 ? SfcRunnerPhase::base
774 sfc_runner_->network_index = 0;
775 sfc_runner_->item_index = 0;
776 sfc_runner_->subitem_index = 0;
777 sfc_runner_->work_remaining = 0;
778 sfc_runner_->reducer = 0;
779 sfc_runner_->action_suppressed = false;
780 sfc_runner_->fault_network_index = invalid_sfc_index;
781 sfc_runner_->fault_element_index = invalid_sfc_index;
782 sfc_runner_->fault_element_kind = TaskFaultElementKind::none;
783 sfc_runner_->trace_scan_begin_size = sfc_runner_->trace_size;
784 sfc_runner_->trace_scan_begin_dropped = sfc_runner_->trace_dropped;
785 return ScanError::ok;
786 }
787
788 void abort() noexcept
789 {
790 if(execution_state_ == InstanceState::running) {
791 if(sfc_commit_started()) rollback_sfc_commit();
792 sfc_runner_->trace_size = sfc_runner_->trace_scan_begin_size;
793 sfc_runner_->trace_dropped = sfc_runner_->trace_scan_begin_dropped;
794 }
795 execution_state_ = InstanceState::idle;
796 pc_ = 0;
797 instruction_pc_ = 0;
798 sp_ = 0;
799 remaining_budget_ = 0;
800 execution_vars_ = vars_;
801 visible_vars_ = vars_;
802 sfc_runner_->active_region = nullptr;
803 sfc_runner_->phase = SfcRunnerPhase::none;
804 sfc_runner_->subitem_index = 0;
805 sfc_runner_->work_remaining = 0;
806 sfc_runner_->reducer = 0;
807 sfc_runner_->action_suppressed = false;
808 }
809
810 // Cycle path. budget = number of instructions this scan may execute;
811 // exact boundary: a program needing N instructions completes with
812 // budget N and faults with budget N-1 (matrix 5.5).
813 ScanError scan(std::int64_t budget)
814 {
815 const ScanError started = begin(budget);
816 if(started != ScanError::ok) return started;
817 std::int64_t executed = 0;
818 return resume(std::numeric_limits<std::int64_t>::max(), executed);
819 }
820
821 // Cooperative execution slice. The slice counts bytecode instructions;
822 // weighted L4 operation costs continue to charge only the task budget.
823 ScanError resume(std::int64_t slice, std::int64_t &executed)
824 {
825 executed = 0;
826 if(program_ == nullptr) return ScanError::not_loaded;
827 if(fault_ != ScanError::ok) return fault_;
828 if(execution_state_ != InstanceState::running) {
829 return execution_state_ == InstanceState::complete
832 }
833 if(slice <= 0) return ScanError::ok;
834 const std::uint8_t *code = nullptr;
835 std::size_t size = 0;
836 const std::uint64_t *constants = nullptr;
837 std::size_t constant_count = 0;
838 std::int32_t stack_limit = 0;
839 const auto select_code = [&]() {
840 if(sfc_runner_->active_region != nullptr) {
841 code = sfc_runner_->active_region->code.data();
842 size = sfc_runner_->active_region->code.size();
843 constants = sfc_runner_->active_region->constants.data();
844 constant_count = sfc_runner_->active_region->constants.size();
845 stack_limit = sfc_runner_->active_region->stack_slots;
846 } else {
847 code = program_->code.data();
848 size = program_->code.size();
849 constants = program_->constants.data();
850 constant_count = program_->constants.size();
851 stack_limit = program_->stack_slots;
852 }
853 };
854 select_code();
855 std::size_t &pc = pc_;
856 std::int32_t &sp = sp_;
857 std::int64_t &remaining = remaining_budget_;
858 const auto charge_operation = [&remaining](std::uint32_t cost) {
859 const std::int64_t extra = cost > 1U
860 ? static_cast<std::int64_t>(cost - 1U)
861 : 0;
862 if(remaining < extra) {
863 return false;
864 }
865 remaining -= extra;
866 return true;
867 };
868
869 for(;;) {
870 if(executed >= slice) return ScanError::ok;
871 if(!program_->sfc_networks.empty() &&
872 sfc_runner_->phase != SfcRunnerPhase::none &&
873 sfc_runner_->phase != SfcRunnerPhase::base && sfc_runner_->active_region == nullptr) {
874 if(remaining <= 0)
875 return latch(ScanError::budget_exceeded);
876 --remaining;
877 ++executed;
878 advance_sfc_runner();
879 if(sfc_runner_->active_region != nullptr) {
880 pc = 0;
881 sp = 0;
882 select_code();
883 continue;
884 }
885 if(sfc_runner_->phase == SfcRunnerPhase::none) {
886 execution_state_ = InstanceState::complete;
887 return ScanError::ok;
888 }
889 continue;
890 }
891 if(remaining <= 0) {
892 return latch(ScanError::budget_exceeded);
893 }
894 --remaining;
895 ++executed;
896 if(pc >= size) {
897 return latch(ScanError::invalid_bytecode);
898 }
899 instruction_pc_ = pc;
900 const Op op = static_cast<Op>(code[pc++]);
901 switch(op) {
902 case Op::debug_probe: {
903 std::uint32_t probe = 0;
904 if(!rd32(code, size, pc, probe))
905 return latch(ScanError::invalid_bytecode);
906 const SourceMap *map = sfc_runner_->active_region == nullptr
907 ? &program_->source_map
908 : &sfc_runner_->active_region->source_map;
909 if(probe >= map->entries.size())
910 return latch(ScanError::invalid_bytecode);
911 DebugRuntimeStorage *runtime = debug_runtime_storage();
912 if(runtime == nullptr)
913 return latch(ScanError::invalid_bytecode);
914 runtime->last_entry = &map->entries[probe];
915 runtime->last_instruction_id = runtime->last_entry->instruction_id;
916 runtime->last_instruction_id.mapping = runtime->mapping;
917 runtime->last_instruction_id.offset =
918 static_cast<std::uint32_t>(instruction_pc_);
919 if(debug_hooks_ != nullptr &&
920 debug_hooks_->on_probe(
921 runtime->mapping, map->entries[probe],
922 static_cast<std::uint32_t>(instruction_pc_))) {
923 pc = instruction_pc_;
924 ++remaining;
925 --executed;
926 return ScanError::paused;
927 }
928 ++remaining;
929 --executed;
930 break;
931 }
932 case Op::halt:
933 if(!program_->sfc_networks.empty()) {
934 if(sfc_runner_->active_region != nullptr)
935 finish_sfc_region();
936 else if(sfc_runner_->phase == SfcRunnerPhase::base)
937 begin_sfc_regions();
938 continue;
939 } else if(process_image_ != nullptr) {
940 process_image_->commit_scan(
941 *program_, vars_, !defer_process_image_publish_);
942 }
943 execution_state_ = InstanceState::complete;
944 return ScanError::ok;
945
946 case Op::push_const: {
947 std::uint16_t index = 0;
948 if(!rd16(code, size, pc, index) || index >= constant_count ||
949 sp >= stack_limit) {
950 return latch(ScanError::invalid_bytecode);
951 }
952 stack_[sp++] = constants[index];
953 break;
954 }
955 case Op::load_var: {
956 std::uint32_t offset = 0;
957 std::uint32_t type = 0;
958 std::uint64_t value = 0;
959 if(!rd32(code, size, pc, offset) ||
960 !rd32(code, size, pc, type) || sp >= stack_limit ||
961 !load_value(offset, type, value)) {
962 return latch(ScanError::invalid_bytecode);
963 }
964 stack_[sp++] = value;
965 break;
966 }
967 case Op::store_var: {
968 std::uint32_t offset = 0;
969 std::uint32_t type = 0;
970 if(!rd32(code, size, pc, offset) ||
971 !rd32(code, size, pc, type) || sp < 1 ||
972 !store_value(offset, type, stack_[sp - 1])) {
973 return latch(ScanError::invalid_bytecode);
974 }
975 --sp;
976 break;
977 }
978 case Op::load_access:
979 case Op::store_access: {
980 std::uint32_t offset = 0;
981 std::uint32_t type = 0;
982 if(!rd32(code, size, pc, offset) ||
983 !rd32(code, size, pc, type) || pc >= size) {
984 return latch(ScanError::invalid_bytecode);
985 }
986 const std::uint8_t count = code[pc++];
987 const int needed = static_cast<int>(count) +
988 (op == Op::store_access ? 1 : 0);
989 if(sp < needed ||
990 (op == Op::load_access &&
991 sp - static_cast<int>(count) >= stack_limit)) {
992 return latch(ScanError::invalid_bytecode);
993 }
994 const int index_base = sp - static_cast<int>(count);
995 for(std::uint8_t i = 0; i < count; ++i) {
996 std::uint64_t lower_raw = 0;
997 std::uint64_t upper_raw = 0;
998 std::uint64_t stride = 0;
999 if(!rd64(code, size, pc, lower_raw) ||
1000 !rd64(code, size, pc, upper_raw) ||
1001 !rd64(code, size, pc, stride)) {
1002 return latch(ScanError::invalid_bytecode);
1003 }
1004 const std::int64_t lower =
1005 static_cast<std::int64_t>(lower_raw);
1006 const std::int64_t upper =
1007 static_cast<std::int64_t>(upper_raw);
1008 const std::int64_t value = as_i64(
1009 stack_[index_base + static_cast<int>(i)]);
1010 if(value < lower || value > upper) {
1011 return latch(ScanError::range_violation);
1012 }
1013 const std::uint64_t delta =
1014 static_cast<std::uint64_t>(value - lower) * stride;
1015 if(delta > std::numeric_limits<std::uint32_t>::max() -
1016 offset) {
1017 return latch(ScanError::invalid_bytecode);
1018 }
1019 offset += static_cast<std::uint32_t>(delta);
1020 }
1021 if(op == Op::load_access) {
1022 std::uint64_t value = 0;
1023 sp -= count;
1024 if(!load_value(offset, type, value)) {
1025 return latch(ScanError::invalid_bytecode);
1026 }
1027 stack_[sp++] = value;
1028 } else {
1029 const std::uint64_t value =
1030 stack_[index_base - 1];
1031 if(!store_value(offset, type, value)) {
1032 return latch(ScanError::invalid_bytecode);
1033 }
1034 sp -= needed;
1035 }
1036 break;
1037 }
1038 case Op::copy_bytes: {
1039 std::uint32_t destination = 0;
1040 std::uint32_t source = 0;
1041 std::uint32_t count = 0;
1042 if(!rd32(code, size, pc, destination) ||
1043 !rd32(code, size, pc, source) ||
1044 !rd32(code, size, pc, count) ||
1045 destination > program_->vars_bytes ||
1046 count > program_->vars_bytes - destination ||
1047 source > program_->vars_bytes ||
1048 count > program_->vars_bytes - source) {
1049 return latch(ScanError::invalid_bytecode);
1050 }
1051 std::memmove(execution_vars_ + destination,
1052 execution_vars_ + source, count);
1053 break;
1054 }
1055 case Op::string_copy:
1056 case Op::string_copy_const: {
1057 std::uint32_t destination = 0;
1058 std::uint32_t destination_type = 0;
1059 std::uint32_t source = 0;
1060 std::uint32_t source_type = 0;
1061 if(!rd32(code, size, pc, destination) ||
1062 !rd32(code, size, pc, destination_type) ||
1063 !rd32(code, size, pc, source) ||
1064 !rd32(code, size, pc, source_type)) {
1065 return latch(ScanError::invalid_bytecode);
1066 }
1067 const TypeDesc *dst = program_->types.get(destination_type);
1068 const TypeDesc *src = program_->types.get(source_type);
1069 if(dst == nullptr || src == nullptr || dst->kind != src->kind ||
1070 (dst->kind != TypeKind::string &&
1071 dst->kind != TypeKind::wstring) ||
1072 destination > program_->vars_bytes ||
1073 dst->size > program_->vars_bytes - destination) {
1074 return latch(ScanError::invalid_bytecode);
1075 }
1076 const std::uint32_t operation_cost = std::max(
1077 dst->string.capacity, src->string.capacity);
1078 if(!charge_operation(operation_cost)) {
1079 return latch(ScanError::budget_exceeded);
1080 }
1081 const unsigned char *source_bytes = nullptr;
1082 if(op == Op::string_copy) {
1083 if(source > program_->vars_bytes ||
1084 src->size > program_->vars_bytes - source) {
1085 return latch(ScanError::invalid_bytecode);
1086 }
1087 source_bytes = execution_vars_ + source;
1088 } else {
1089 if(source > program_->string_constants.size() ||
1090 4U > program_->string_constants.size() - source) {
1091 return latch(ScanError::invalid_bytecode);
1092 }
1093 source_bytes = program_->string_constants.data() + source;
1094 }
1095 const std::uint32_t length = read_le32(source_bytes);
1096 if(length > src->string.capacity) {
1097 return latch(ScanError::invalid_bytecode);
1098 }
1099 const std::uint64_t width =
1100 dst->kind == TypeKind::wstring ? 4U : 1U;
1101 const std::uint64_t count = 4U + width * length;
1102 if(op == Op::string_copy_const &&
1103 count > program_->string_constants.size() - source) {
1104 return latch(ScanError::invalid_bytecode);
1105 }
1106 if(!valid_string_object(source_bytes, *src)) {
1107 return latch(ScanError::invalid_bytecode);
1108 }
1109 if(length > dst->string.capacity) {
1111 }
1112 if(op == Op::string_copy && source == destination) {
1113 break;
1114 }
1115 std::memset(execution_vars_ + destination, 0,
1116 static_cast<std::size_t>(dst->size));
1117 std::memmove(execution_vars_ + destination, source_bytes,
1118 static_cast<std::size_t>(count));
1119 break;
1120 }
1121 case Op::string_compare: {
1122 if(pc >= size) {
1123 return latch(ScanError::invalid_bytecode);
1124 }
1125 const std::uint8_t comparison = code[pc++];
1126 const unsigned char *objects[2] = {nullptr, nullptr};
1127 const TypeDesc *descs[2] = {nullptr, nullptr};
1128 for(int i = 0; i < 2; ++i) {
1129 if(pc >= size) {
1130 return latch(ScanError::invalid_bytecode);
1131 }
1132 const std::uint8_t constant = code[pc++];
1133 std::uint32_t offset = 0;
1134 std::uint32_t id = 0;
1135 if(!rd32(code, size, pc, offset) ||
1136 !rd32(code, size, pc, id)) {
1137 return latch(ScanError::invalid_bytecode);
1138 }
1139 descs[i] = program_->types.get(id);
1140 if(descs[i] == nullptr ||
1141 (descs[i]->kind != TypeKind::string &&
1142 descs[i]->kind != TypeKind::wstring)) {
1143 return latch(ScanError::invalid_bytecode);
1144 }
1145 if(constant != 0) {
1146 if(offset > program_->string_constants.size() ||
1147 4U > program_->string_constants.size() - offset) {
1148 return latch(ScanError::invalid_bytecode);
1149 }
1150 objects[i] = program_->string_constants.data() + offset;
1151 const std::uint32_t length = read_le32(objects[i]);
1152 const std::uint64_t object_size = 4U +
1153 static_cast<std::uint64_t>(length) *
1154 (descs[i]->kind == TypeKind::wstring ? 4U : 1U);
1155 if(length > descs[i]->string.capacity ||
1156 object_size >
1157 program_->string_constants.size() - offset) {
1158 return latch(ScanError::invalid_bytecode);
1159 }
1160 } else {
1161 if(offset > program_->vars_bytes ||
1162 descs[i]->size > program_->vars_bytes - offset) {
1163 return latch(ScanError::invalid_bytecode);
1164 }
1165 objects[i] = execution_vars_ + offset;
1166 }
1167 }
1168 if(descs[0]->kind != descs[1]->kind || sp >= stack_limit) {
1169 return latch(ScanError::invalid_bytecode);
1170 }
1171 const std::uint32_t operation_cost = std::max(
1172 descs[0]->string.capacity, descs[1]->string.capacity);
1173 if(!charge_operation(operation_cost)) {
1174 return latch(ScanError::budget_exceeded);
1175 }
1176 const int order = compare_strings(objects[0], *descs[0],
1177 objects[1], *descs[1]);
1178 if(order == 2) {
1179 return latch(ScanError::invalid_bytecode);
1180 }
1181 bool result = false;
1182 switch(comparison) {
1183 case 8: result = order == 0; break;
1184 case 9: result = order != 0; break;
1185 case 10: result = order < 0; break;
1186 case 11: result = order > 0; break;
1187 case 12: result = order <= 0; break;
1188 case 13: result = order >= 0; break;
1189 default: return latch(ScanError::invalid_bytecode);
1190 }
1191 stack_[sp++] = result ? 1U : 0U;
1192 break;
1193 }
1194 case Op::string_index: {
1195 std::uint32_t offset = 0;
1196 std::uint32_t id = 0;
1197 if(!rd32(code, size, pc, offset) ||
1198 !rd32(code, size, pc, id) || sp < 1) {
1199 return latch(ScanError::invalid_bytecode);
1200 }
1201 const TypeDesc *desc = program_->types.get(id);
1202 if(desc == nullptr ||
1203 (desc->kind != TypeKind::string &&
1204 desc->kind != TypeKind::wstring) ||
1205 offset > program_->vars_bytes ||
1206 desc->size > program_->vars_bytes - offset) {
1207 return latch(ScanError::invalid_bytecode);
1208 }
1209 if(!charge_operation(desc->string.capacity)) {
1210 return latch(ScanError::budget_exceeded);
1211 }
1212 if(!valid_string_object(execution_vars_ + offset, *desc)) {
1213 return latch(ScanError::invalid_bytecode);
1214 }
1215 const std::int64_t index = as_i64(stack_[sp - 1]);
1216 const std::uint32_t length = read_le32(execution_vars_ + offset);
1217 if(index < 1 || static_cast<std::uint64_t>(index) > length) {
1218 return latch(ScanError::range_violation);
1219 }
1220 if(desc->kind == TypeKind::wstring) {
1221 stack_[sp - 1] = read_le32(
1222 execution_vars_ + offset + 4U +
1223 (static_cast<std::size_t>(index) - 1U) * 4U);
1224 } else {
1225 stack_[sp - 1] = execution_vars_[offset + 4U +
1226 static_cast<std::uint32_t>(index) - 1U];
1227 }
1228 break;
1229 }
1230 case Op::check_unicode:
1231 if(sp < 1) {
1232 return latch(ScanError::invalid_bytecode);
1233 }
1234 if(stack_[sp - 1] > 0x10FFFFU ||
1235 (stack_[sp - 1] >= 0xD800U &&
1236 stack_[sp - 1] <= 0xDFFFU)) {
1237 return latch(ScanError::conversion_invalid);
1238 }
1239 break;
1240 case Op::date_arith: {
1241 if(pc >= size || sp < 2) {
1242 return latch(ScanError::invalid_bytecode);
1243 }
1244 const std::uint8_t kind = code[pc++];
1245 const std::int64_t right = as_i64(stack_[--sp]);
1246 const std::int64_t left = as_i64(stack_[sp - 1]);
1247 std::int64_t value = 0;
1248 if(kind <= 1U) {
1249 const std::int64_t delta = kind == 0U ? right : -right;
1250 value = left + delta;
1251 if(value < std::numeric_limits<std::int32_t>::min() ||
1252 value > std::numeric_limits<std::int32_t>::max()) {
1254 }
1255 } else if(kind <= 3U) {
1256 constexpr std::int64_t day = 86400000000000LL;
1257 const std::int64_t delta = right % day;
1258 value = kind == 2U ? left + delta : left - delta;
1259 value %= day;
1260 if(value < 0) {
1261 value += day;
1262 }
1263 } else if(kind <= 5U) {
1264 if((kind == 4U &&
1265 ((right > 0 && left >
1266 std::numeric_limits<std::int64_t>::max() - right) ||
1267 (right < 0 && left <
1268 std::numeric_limits<std::int64_t>::min() - right))) ||
1269 (kind == 5U &&
1270 ((right < 0 && left >
1271 std::numeric_limits<std::int64_t>::max() + right) ||
1272 (right > 0 && left <
1273 std::numeric_limits<std::int64_t>::min() + right)))) {
1275 }
1276 value = kind == 4U ? left + right : left - right;
1277 } else {
1278 return latch(ScanError::invalid_bytecode);
1279 }
1280 stack_[sp - 1] = static_cast<std::uint64_t>(value);
1281 break;
1282 }
1283
1284 case Op::add_int:
1285 case Op::sub_int:
1286 case Op::mul_int:
1287 case Op::add_dint:
1288 case Op::sub_dint:
1289 case Op::mul_dint:
1290 case Op::add_time:
1291 case Op::sub_time: {
1292 if(sp < 2) {
1293 return latch(ScanError::invalid_bytecode);
1294 }
1295 const std::int64_t b = as_i64(stack_[--sp]);
1296 const std::int64_t a = as_i64(stack_[--sp]);
1297 std::int64_t value = 0;
1298 switch(op) {
1299 case Op::add_int:
1300 value = detail::wrap16(detail::wrap_add64(a, b));
1301 break;
1302 case Op::sub_int:
1303 value = detail::wrap16(detail::wrap_sub64(a, b));
1304 break;
1305 case Op::mul_int:
1306 value = detail::wrap16(detail::wrap_mul64(a, b));
1307 break;
1308 case Op::add_dint:
1309 value = detail::wrap32(detail::wrap_add64(a, b));
1310 break;
1311 case Op::sub_dint:
1312 value = detail::wrap32(detail::wrap_sub64(a, b));
1313 break;
1314 case Op::mul_dint:
1315 value = detail::wrap32(detail::wrap_mul64(a, b));
1316 break;
1317 case Op::add_time:
1318 value = detail::wrap_add64(a, b);
1319 break;
1320 default:
1321 value = detail::wrap_sub64(a, b);
1322 break;
1323 }
1324 stack_[sp++] = as_u64(value);
1325 break;
1326 }
1327
1328 case Op::div_int:
1329 case Op::mod_int:
1330 case Op::div_dint:
1331 case Op::mod_dint: {
1332 if(sp < 2) {
1333 return latch(ScanError::invalid_bytecode);
1334 }
1335 const std::int64_t b = as_i64(stack_[--sp]);
1336 const std::int64_t a = as_i64(stack_[--sp]);
1337 if(b == 0) {
1338 return latch(ScanError::division_by_zero);
1339 }
1340 std::int64_t value = 0;
1341 switch(op) {
1342 case Op::div_int:
1343 value = detail::wrap16(a / b);
1344 break;
1345 case Op::mod_int:
1346 value = detail::wrap16(a % b);
1347 break;
1348 case Op::div_dint:
1349 value = detail::wrap32(a / b);
1350 break;
1351 default:
1352 value = detail::wrap32(a % b);
1353 break;
1354 }
1355 stack_[sp++] = as_u64(value);
1356 break;
1357 }
1358
1359 case Op::neg_int:
1360 case Op::neg_dint: {
1361 if(sp < 1) {
1362 return latch(ScanError::invalid_bytecode);
1363 }
1364 const std::int64_t a = as_i64(stack_[--sp]);
1365 const std::int64_t value =
1366 op == Op::neg_int
1369 stack_[sp++] = as_u64(value);
1370 break;
1371 }
1372
1373 case Op::add_real:
1374 case Op::sub_real:
1375 case Op::mul_real:
1376 case Op::div_real: {
1377 if(sp < 2) {
1378 return latch(ScanError::invalid_bytecode);
1379 }
1380 const float b =
1381 static_cast<float>(detail::bits_double(stack_[--sp]));
1382 const float a =
1383 static_cast<float>(detail::bits_double(stack_[--sp]));
1384 float value = 0.0F;
1385 switch(op) {
1386 case Op::add_real: value = a + b; break;
1387 case Op::sub_real: value = a - b; break;
1388 case Op::mul_real: value = a * b; break;
1389 default: value = a / b; break;
1390 }
1391 stack_[sp++] =
1392 detail::double_bits(static_cast<double>(value));
1393 break;
1394 }
1395 case Op::neg_real: {
1396 if(sp < 1) {
1397 return latch(ScanError::invalid_bytecode);
1398 }
1399 const float a =
1400 static_cast<float>(detail::bits_double(stack_[--sp]));
1401 stack_[sp++] =
1402 detail::double_bits(static_cast<double>(-a));
1403 break;
1404 }
1405
1406 case Op::add_lreal:
1407 case Op::sub_lreal:
1408 case Op::mul_lreal:
1409 case Op::div_lreal: {
1410 if(sp < 2) {
1411 return latch(ScanError::invalid_bytecode);
1412 }
1413 const double b = detail::bits_double(stack_[--sp]);
1414 const double a = detail::bits_double(stack_[--sp]);
1415 double value = 0.0;
1416 switch(op) {
1417 case Op::add_lreal: value = a + b; break;
1418 case Op::sub_lreal: value = a - b; break;
1419 case Op::mul_lreal: value = a * b; break;
1420 default: value = a / b; break;
1421 }
1422 stack_[sp++] = detail::double_bits(value);
1423 break;
1424 }
1425 case Op::neg_lreal: {
1426 if(sp < 1) {
1427 return latch(ScanError::invalid_bytecode);
1428 }
1429 const double a = detail::bits_double(stack_[--sp]);
1430 stack_[sp++] = detail::double_bits(-a);
1431 break;
1432 }
1433
1434 case Op::and_bool:
1435 case Op::or_bool:
1436 case Op::xor_bool: {
1437 if(sp < 2) {
1438 return latch(ScanError::invalid_bytecode);
1439 }
1440 const bool b = stack_[--sp] != 0;
1441 const bool a = stack_[--sp] != 0;
1442 bool value = false;
1443 if(op == Op::and_bool) {
1444 value = a && b;
1445 } else if(op == Op::or_bool) {
1446 value = a || b;
1447 } else {
1448 value = a != b;
1449 }
1450 stack_[sp++] = value ? 1 : 0;
1451 break;
1452 }
1453 case Op::not_bool: {
1454 if(sp < 1) {
1455 return latch(ScanError::invalid_bytecode);
1456 }
1457 stack_[sp - 1] = stack_[sp - 1] == 0 ? 1 : 0;
1458 break;
1459 }
1460
1461 case Op::cmp_eq_i:
1462 case Op::cmp_ne_i:
1463 case Op::cmp_lt_i:
1464 case Op::cmp_gt_i:
1465 case Op::cmp_le_i:
1466 case Op::cmp_ge_i: {
1467 if(sp < 2) {
1468 return latch(ScanError::invalid_bytecode);
1469 }
1470 const std::int64_t b = as_i64(stack_[--sp]);
1471 const std::int64_t a = as_i64(stack_[--sp]);
1472 bool value = false;
1473 switch(op) {
1474 case Op::cmp_eq_i: value = a == b; break;
1475 case Op::cmp_ne_i: value = a != b; break;
1476 case Op::cmp_lt_i: value = a < b; break;
1477 case Op::cmp_gt_i: value = a > b; break;
1478 case Op::cmp_le_i: value = a <= b; break;
1479 default: value = a >= b; break;
1480 }
1481 stack_[sp++] = value ? 1 : 0;
1482 break;
1483 }
1484
1485 case Op::cmp_eq_f:
1486 case Op::cmp_ne_f:
1487 case Op::cmp_lt_f:
1488 case Op::cmp_gt_f:
1489 case Op::cmp_le_f:
1490 case Op::cmp_ge_f: {
1491 if(sp < 2) {
1492 return latch(ScanError::invalid_bytecode);
1493 }
1494 const double b = detail::bits_double(stack_[--sp]);
1495 const double a = detail::bits_double(stack_[--sp]);
1496 bool value = false;
1497 switch(op) {
1498 case Op::cmp_eq_f: value = a == b; break;
1499 case Op::cmp_ne_f: value = a != b; break;
1500 case Op::cmp_lt_f: value = a < b; break;
1501 case Op::cmp_gt_f: value = a > b; break;
1502 case Op::cmp_le_f: value = a <= b; break;
1503 default: value = a >= b; break;
1504 }
1505 stack_[sp++] = value ? 1 : 0;
1506 break;
1507 }
1508
1509 case Op::jmp: {
1510 std::uint32_t target = 0;
1511 if(!rd32(code, size, pc, target) || target > size) {
1512 return latch(ScanError::invalid_bytecode);
1513 }
1514 pc = target;
1515 break;
1516 }
1517 case Op::jmp_if_false: {
1518 std::uint32_t target = 0;
1519 if(!rd32(code, size, pc, target) || target > size || sp < 1) {
1520 return latch(ScanError::invalid_bytecode);
1521 }
1522 if(stack_[--sp] == 0) {
1523 pc = target;
1524 }
1525 break;
1526 }
1527
1528 case Op::for_guard: {
1529 std::uint32_t offset = 0;
1530 std::uint64_t value = 0;
1531 if(!rd32(code, size, pc, offset) ||
1532 !load_raw64(offset, value)) {
1533 return latch(ScanError::invalid_bytecode);
1534 }
1535 if(as_i64(value) == 0) {
1536 return latch(ScanError::for_step_zero);
1537 }
1538 break;
1539 }
1540 case Op::for_test: {
1541 std::uint32_t ctrl = 0;
1542 std::uint32_t to = 0;
1543 std::uint32_t by = 0;
1544 std::uint32_t type = 0;
1545 std::uint64_t control_raw = 0;
1546 std::uint64_t bound_raw = 0;
1547 std::uint64_t step_raw = 0;
1548 if(!rd32(code, size, pc, ctrl) || !rd32(code, size, pc, to) ||
1549 !rd32(code, size, pc, by) || !rd32(code, size, pc, type) ||
1550 sp >= stack_limit || !load_value(ctrl, type, control_raw) ||
1551 !load_value(to, type, bound_raw) ||
1552 !load_value(by, type, step_raw)) {
1553 return latch(ScanError::invalid_bytecode);
1554 }
1555 const std::int64_t control = as_i64(control_raw);
1556 const std::int64_t bound = as_i64(bound_raw);
1557 const std::int64_t step = as_i64(step_raw);
1558 const bool keep_running =
1559 step >= 0 ? control <= bound : control >= bound;
1560 stack_[sp++] = keep_running ? 1 : 0;
1561 break;
1562 }
1563 case Op::for_step_int:
1564 case Op::for_step_dint: {
1565 std::uint32_t ctrl = 0;
1566 std::uint32_t by = 0;
1567 std::uint32_t type = 0;
1568 std::uint64_t control = 0;
1569 std::uint64_t step = 0;
1570 if(!rd32(code, size, pc, ctrl) || !rd32(code, size, pc, by) ||
1571 !rd32(code, size, pc, type) ||
1572 !load_value(ctrl, type, control) ||
1573 !load_value(by, type, step)) {
1574 return latch(ScanError::invalid_bytecode);
1575 }
1576 const std::int64_t stepped = detail::wrap_add64(
1577 as_i64(control), as_i64(step));
1578 const std::uint64_t stored = as_u64(
1579 op == Op::for_step_int ? detail::wrap16(stepped)
1580 : detail::wrap32(stepped));
1581 if(!store_value(ctrl, type, stored)) {
1582 return latch(ScanError::invalid_bytecode);
1583 }
1584 break;
1585 }
1586
1587 case Op::fb_store_in: {
1588 std::uint16_t fb = 0;
1589 if(!rd16(code, size, pc, fb) || pc >= size || sp < 1 ||
1590 fb >= program_->fbs.size()) {
1591 return latch(ScanError::invalid_bytecode);
1592 }
1593 const std::uint8_t pin = code[pc++];
1594 const FbInfo &info = program_->fbs[fb];
1595 if(pin >= pin_table(info.type).count) {
1596 return latch(ScanError::invalid_bytecode);
1597 }
1598 std::int64_t value = as_i64(stack_[--sp]);
1599 const PinDesc &pin_desc = pin_table(info.type).pins[pin];
1601 info.type, pin)) {
1603 if(!resolve_tagged_reference_payload(
1604 pin_desc.type_id, value, tagged) ||
1606 info.type, fb_area_ + info.offset, pin,
1607 pin_desc.type_id, tagged)) {
1608 return latch(ScanError::invalid_bytecode);
1609 }
1610 break;
1611 }
1614 if(!resolve_sequence_payload(pin_desc.type_id, value,
1615 sequence) ||
1616 !fb_store_sequence(info.type, fb_area_ + info.offset,
1617 pin, sequence)) {
1618 return latch(ScanError::invalid_bytecode);
1619 }
1620 break;
1621 }
1622 const Type pin_type = pin_desc.type;
1623 if(!resolve_reference_payload(pin_type, pin_desc.type_id,
1624 value)) {
1625 return latch(ScanError::invalid_bytecode);
1626 }
1627 if(!fb_store_scalar(info.type, fb_area_ + info.offset, pin,
1628 as_u64(value))) {
1629 return latch(ScanError::invalid_bytecode);
1630 }
1631 break;
1632 }
1633 case Op::fb_store_object: {
1634 std::uint16_t fb = 0;
1635 std::uint32_t offset = 0;
1636 std::uint32_t type_id = 0;
1637 if(!rd16(code, size, pc, fb) || pc >= size ||
1638 fb >= program_->fbs.size()) {
1639 return latch(ScanError::invalid_bytecode);
1640 }
1641 const std::uint8_t pin = code[pc++];
1642 if(!rd32(code, size, pc, offset) ||
1643 !rd32(code, size, pc, type_id)) {
1644 return latch(ScanError::invalid_bytecode);
1645 }
1646 const FbInfo &info = program_->fbs[fb];
1647 const TypeDesc *desc = program_->types.get(type_id);
1648 if(pin >= pin_table(info.type).count || desc == nullptr ||
1649 (desc->kind != TypeKind::array &&
1650 desc->kind != TypeKind::struct_ &&
1651 desc->kind != TypeKind::string &&
1652 desc->kind != TypeKind::wstring) ||
1653 offset > program_->vars_bytes ||
1654 desc->size > program_->vars_bytes - offset ||
1655 !charge_operation(static_cast<std::uint32_t>(desc->size)) ||
1656 !fb_store_object(info.type, fb_area_ + info.offset, pin,
1657 execution_vars_ + offset, type_id,
1658 static_cast<std::uint32_t>(desc->size))) {
1659 return latch(ScanError::invalid_bytecode);
1660 }
1661 break;
1662 }
1663 case Op::fb_call: {
1664 std::uint16_t fb = 0;
1665 if(!rd16(code, size, pc, fb) || fb >= program_->fbs.size()) {
1666 return latch(ScanError::invalid_bytecode);
1667 }
1668 const FbInfo &info = program_->fbs[fb];
1669 fb_cycle(info.type, fb_area_ + info.offset, task_period_ns_);
1670 break;
1671 }
1672 case Op::fb_load_out: {
1673 std::uint16_t fb = 0;
1674 if(!rd16(code, size, pc, fb) || pc >= size ||
1675 sp >= stack_limit || fb >= program_->fbs.size()) {
1676 return latch(ScanError::invalid_bytecode);
1677 }
1678 const std::uint8_t pin = code[pc++];
1679 const FbInfo &info = program_->fbs[fb];
1680 if(pin >= pin_table(info.type).count) {
1681 return latch(ScanError::invalid_bytecode);
1682 }
1683 const PinDesc &pin_desc = pin_table(info.type).pins[pin];
1685 info.type, pin)) {
1687 std::int64_t handle = 0;
1689 info.type, fb_area_ + info.offset, pin,
1690 pin_desc.type_id, tagged) ||
1691 !encode_tagged_reference_payload(
1692 pin_desc.type_id, tagged, handle)) {
1693 return latch(ScanError::invalid_bytecode);
1694 }
1695 stack_[sp++] = as_u64(handle);
1696 break;
1697 }
1700 std::int64_t handle = 0;
1701 if(!fb_load_sequence(info.type, fb_area_ + info.offset,
1702 pin, sequence) ||
1703 !encode_sequence_payload(pin_desc.type_id, sequence,
1704 handle)) {
1705 return latch(ScanError::invalid_bytecode);
1706 }
1707 stack_[sp++] = as_u64(handle);
1708 break;
1709 }
1710 std::uint64_t value = 0;
1711 if(!fb_load_scalar(info.type, fb_area_ + info.offset, pin,
1712 value)) {
1713 return latch(ScanError::invalid_bytecode);
1714 }
1715 std::int64_t resolved = as_i64(value);
1716 if(!encode_reference_payload(pin_desc.type, pin_desc.type_id,
1717 resolved)) {
1718 return latch(ScanError::invalid_bytecode);
1719 }
1720 stack_[sp++] = as_u64(resolved);
1721 break;
1722 }
1723 case Op::fb_load_object: {
1724 std::uint16_t fb = 0;
1725 std::uint32_t offset = 0;
1726 std::uint32_t type_id = 0;
1727 if(!rd16(code, size, pc, fb) || pc >= size ||
1728 fb >= program_->fbs.size()) {
1729 return latch(ScanError::invalid_bytecode);
1730 }
1731 const std::uint8_t pin = code[pc++];
1732 if(!rd32(code, size, pc, offset) ||
1733 !rd32(code, size, pc, type_id)) {
1734 return latch(ScanError::invalid_bytecode);
1735 }
1736 const FbInfo &info = program_->fbs[fb];
1737 const TypeDesc *desc = program_->types.get(type_id);
1738 if(pin >= pin_table(info.type).count || desc == nullptr ||
1739 (desc->kind != TypeKind::array &&
1740 desc->kind != TypeKind::struct_) ||
1741 offset > program_->vars_bytes ||
1742 desc->size > program_->vars_bytes - offset ||
1743 !charge_operation(static_cast<std::uint32_t>(desc->size)) ||
1744 !fb_load_object(info.type, fb_area_ + info.offset, pin,
1745 execution_vars_ + offset, type_id,
1746 static_cast<std::uint32_t>(desc->size))) {
1747 return latch(ScanError::invalid_bytecode);
1748 }
1749 break;
1750 }
1751
1752 // --- L1a extensions (approved st-l1a-semantics) --------------
1753
1754 case Op::iarith: {
1755 if(pc + 2 > size) {
1756 return latch(ScanError::invalid_bytecode);
1757 }
1758 const std::uint8_t sub = code[pc++];
1759 const Type type = static_cast<Type>(code[pc++]);
1760 if(sub == 5) { // neg (signed only)
1761 if(sp < 1) {
1762 return latch(ScanError::invalid_bytecode);
1763 }
1764 const std::int64_t a = as_i64(stack_[sp - 1]);
1765 stack_[sp - 1] = detail::canon(
1766 type,
1767 static_cast<std::uint64_t>(detail::wrap_sub64(0, a)));
1768 break;
1769 }
1770 if(sp < 2) {
1771 return latch(ScanError::invalid_bytecode);
1772 }
1773 const std::uint64_t rb = stack_[--sp];
1774 const std::uint64_t ra = stack_[--sp];
1775 std::uint64_t bits = 0;
1776 if(is_unsigned_int(type)) {
1777 switch(sub) {
1778 case 0: bits = ra + rb; break;
1779 case 1: bits = ra - rb; break;
1780 case 2: bits = ra * rb; break;
1781 case 3:
1782 if(rb == 0) {
1783 return latch(ScanError::division_by_zero);
1784 }
1785 bits = ra / rb;
1786 break;
1787 case 4:
1788 if(rb == 0) {
1789 return latch(ScanError::division_by_zero);
1790 }
1791 bits = ra % rb;
1792 break;
1793 default:
1794 return latch(ScanError::invalid_bytecode);
1795 }
1796 } else {
1797 const std::int64_t a = as_i64(ra);
1798 const std::int64_t b = as_i64(rb);
1799 std::int64_t value = 0;
1800 switch(sub) {
1801 case 0: value = detail::wrap_add64(a, b); break;
1802 case 1: value = detail::wrap_sub64(a, b); break;
1803 case 2: value = detail::wrap_mul64(a, b); break;
1804 case 3:
1805 if(b == 0) {
1806 return latch(ScanError::division_by_zero);
1807 }
1808 value = b == -1 ? detail::wrap_sub64(0, a) : a / b;
1809 break;
1810 case 4:
1811 if(b == 0) {
1812 return latch(ScanError::division_by_zero);
1813 }
1814 value = b == -1 ? 0 : a % b;
1815 break;
1816 default:
1817 return latch(ScanError::invalid_bytecode);
1818 }
1819 bits = static_cast<std::uint64_t>(value);
1820 }
1821 stack_[sp++] = detail::canon(type, bits);
1822 break;
1823 }
1824
1825 case Op::cmp_u: {
1826 if(pc >= size || sp < 2) {
1827 return latch(ScanError::invalid_bytecode);
1828 }
1829 const std::uint8_t sub = code[pc++];
1830 const std::uint64_t b = stack_[--sp];
1831 const std::uint64_t a = stack_[--sp];
1832 bool value = false;
1833 switch(sub) {
1834 case 0: value = a < b; break;
1835 case 1: value = a > b; break;
1836 case 2: value = a <= b; break;
1837 case 3: value = a >= b; break;
1838 default:
1839 return latch(ScanError::invalid_bytecode);
1840 }
1841 stack_[sp++] = value ? 1 : 0;
1842 break;
1843 }
1844
1845 case Op::bit_and:
1846 case Op::bit_or:
1847 case Op::bit_xor: {
1848 if(sp < 2) {
1849 return latch(ScanError::invalid_bytecode);
1850 }
1851 const std::uint64_t b = stack_[--sp];
1852 const std::uint64_t a = stack_[--sp];
1853 stack_[sp++] = op == Op::bit_and
1854 ? (a & b)
1855 : (op == Op::bit_or ? (a | b) : (a ^ b));
1856 break;
1857 }
1858 case Op::bit_not: {
1859 if(pc >= size || sp < 1) {
1860 return latch(ScanError::invalid_bytecode);
1861 }
1862 const Type type = static_cast<Type>(code[pc++]);
1863 stack_[sp - 1] = detail::canon(type, ~stack_[sp - 1]);
1864 break;
1865 }
1866
1867 case Op::time_scale: {
1868 if(pc >= size || sp < 2) {
1869 return latch(ScanError::invalid_bytecode);
1870 }
1871 const std::uint8_t sub = code[pc++];
1872 const std::uint64_t rs = stack_[--sp];
1873 const std::int64_t t = as_i64(stack_[--sp]);
1874 std::uint64_t bits = 0;
1875 switch(sub) {
1876 case 0:
1877 bits = static_cast<std::uint64_t>(
1878 detail::wrap_mul64(t, as_i64(rs)));
1879 break;
1880 case 1: {
1881 const std::int64_t s = as_i64(rs);
1882 if(s == 0) {
1883 return latch(ScanError::division_by_zero);
1884 }
1885 bits = static_cast<std::uint64_t>(
1886 s == -1 ? detail::wrap_sub64(0, t) : t / s);
1887 break;
1888 }
1889 case 2:
1890 case 3: {
1891 const double s = detail::bits_double(rs);
1892 const double value = sub == 2
1893 ? static_cast<double>(t) * s
1894 : static_cast<double>(t) / s;
1895 if(!std::isfinite(value)) {
1896 return latch(ScanError::conversion_invalid);
1897 }
1898 bits = detail::wrap_double_to_u64(std::trunc(value));
1899 break;
1900 }
1901 default:
1902 return latch(ScanError::invalid_bytecode);
1903 }
1904 stack_[sp++] = bits;
1905 break;
1906 }
1907
1908 case Op::power: {
1909 if(pc >= size || sp < 2) {
1910 return latch(ScanError::invalid_bytecode);
1911 }
1912 const Type type = static_cast<Type>(code[pc++]);
1913 const double b = detail::bits_double(stack_[--sp]);
1914 const double a = detail::bits_double(stack_[--sp]);
1915 const double value = std::pow(a, b);
1916 stack_[sp++] =
1917 type == Type::real
1918 ? detail::double_bits(static_cast<double>(
1919 static_cast<float>(value)))
1920 : detail::double_bits(value);
1921 break;
1922 }
1923
1924 case Op::conv_wrap: {
1925 if(pc >= size || sp < 1) {
1926 return latch(ScanError::invalid_bytecode);
1927 }
1928 const Type type = static_cast<Type>(code[pc++]);
1929 stack_[sp - 1] = detail::canon(type, stack_[sp - 1]);
1930 break;
1931 }
1932 case Op::conv_i2d: {
1933 if(sp < 1) {
1934 return latch(ScanError::invalid_bytecode);
1935 }
1936 stack_[sp - 1] = detail::double_bits(
1937 static_cast<double>(as_i64(stack_[sp - 1])));
1938 break;
1939 }
1940 case Op::conv_u2d: {
1941 if(sp < 1) {
1942 return latch(ScanError::invalid_bytecode);
1943 }
1944 stack_[sp - 1] = detail::double_bits(
1945 static_cast<double>(stack_[sp - 1]));
1946 break;
1947 }
1948 case Op::f_narrow: {
1949 if(sp < 1) {
1950 return latch(ScanError::invalid_bytecode);
1951 }
1952 stack_[sp - 1] = detail::double_bits(static_cast<double>(
1953 static_cast<float>(detail::bits_double(stack_[sp - 1]))));
1954 break;
1955 }
1956 case Op::conv_round:
1957 case Op::conv_trunc: {
1958 if(pc >= size || sp < 1) {
1959 return latch(ScanError::invalid_bytecode);
1960 }
1961 const Type type = static_cast<Type>(code[pc++]);
1962 const double value = detail::bits_double(stack_[sp - 1]);
1963 if(!std::isfinite(value)) {
1964 return latch(ScanError::conversion_invalid);
1965 }
1966 const double adjusted = op == Op::conv_trunc
1967 ? std::trunc(value)
1968 : std::nearbyint(value);
1969 stack_[sp - 1] = detail::canon(
1970 type, detail::wrap_double_to_u64(adjusted));
1971 break;
1972 }
1973 case Op::conv_to_bool: {
1974 if(sp < 1) {
1975 return latch(ScanError::invalid_bytecode);
1976 }
1977 stack_[sp - 1] = stack_[sp - 1] != 0 ? 1 : 0;
1978 break;
1979 }
1980 case Op::conv_f_to_bool: {
1981 if(sp < 1) {
1982 return latch(ScanError::invalid_bytecode);
1983 }
1984 stack_[sp - 1] =
1985 detail::bits_double(stack_[sp - 1]) != 0.0 ? 1 : 0;
1986 break;
1987 }
1988 case Op::check_range: {
1989 std::uint32_t id = 0;
1990 if(!rd32(code, size, pc, id) || sp < 1) {
1991 return latch(ScanError::invalid_bytecode);
1992 }
1993 const TypeDesc *desc = program_->types.get(id);
1994 if(desc == nullptr ||
1995 (desc->kind != TypeKind::enum_ &&
1996 desc->kind != TypeKind::subrange)) {
1997 return latch(ScanError::invalid_bytecode);
1998 }
1999 const std::uint64_t bits = stack_[sp - 1];
2000 bool valid = false;
2001 if(desc->kind == TypeKind::enum_) {
2002 for(const EnumItem &item : desc->enum_items) {
2003 if(static_cast<std::uint64_t>(item.value.as_signed()) ==
2004 bits) {
2005 valid = true;
2006 break;
2007 }
2008 }
2009 } else if(desc->integer_sign == IntegerSign::signed_) {
2010 const std::int64_t value = as_i64(bits);
2011 valid = value >= desc->subrange.lower.as_signed() &&
2012 value <= desc->subrange.upper.as_signed();
2013 } else {
2014 valid = bits >= desc->subrange.lower.as_unsigned() &&
2015 bits <= desc->subrange.upper.as_unsigned();
2016 }
2017 if(!valid) {
2018 return latch(ScanError::range_violation);
2019 }
2020 break;
2021 }
2022 case Op::commit_outputs: {
2023 std::uint16_t count = 0;
2024 std::uint16_t dynamic_count = 0;
2025 if(!rd16(code, size, pc, count) ||
2026 !rd16(code, size, pc, dynamic_count) || count > 256U ||
2027 sp < static_cast<std::int32_t>(dynamic_count)) {
2028 return latch(ScanError::invalid_bytecode);
2029 }
2030 if(!charge_operation(count)) {
2031 return latch(ScanError::budget_exceeded);
2032 }
2033 // A commit is not observable unless the bytecode stream can
2034 // also reach at least its next instruction. This preserves
2035 // the exact N/N-1 watchdog boundary for a terminal call:
2036 // N-1 faults before publishing any OUTPUT value.
2037 if(remaining <= 0) {
2038 return latch(ScanError::budget_exceeded);
2039 }
2040 std::uint32_t destinations[256] = {};
2041 std::uint32_t sources[256] = {};
2042 std::uint32_t bytes[256] = {};
2043 const std::int32_t index_base =
2044 sp - static_cast<std::int32_t>(dynamic_count);
2045 std::int32_t index_at = index_base;
2046 for(std::uint16_t item = 0; item < count; ++item) {
2047 std::uint32_t source = 0;
2048 std::uint32_t source_type = 0;
2049 std::uint32_t destination = 0;
2050 std::uint32_t destination_type = 0;
2051 if(!rd32(code, size, pc, source) ||
2052 !rd32(code, size, pc, source_type) ||
2053 !rd32(code, size, pc, destination) ||
2054 !rd32(code, size, pc, destination_type) || pc >= size) {
2055 return latch(ScanError::invalid_bytecode);
2056 }
2057 const std::uint8_t indices = code[pc++];
2058 if(index_at + indices > sp) {
2059 return latch(ScanError::invalid_bytecode);
2060 }
2061 for(std::uint8_t i = 0; i < indices; ++i) {
2062 std::uint64_t lower_raw = 0;
2063 std::uint64_t upper_raw = 0;
2064 std::uint64_t stride = 0;
2065 if(!rd64(code, size, pc, lower_raw) ||
2066 !rd64(code, size, pc, upper_raw) ||
2067 !rd64(code, size, pc, stride)) {
2068 return latch(ScanError::invalid_bytecode);
2069 }
2070 const std::int64_t lower =
2071 static_cast<std::int64_t>(lower_raw);
2072 const std::int64_t upper =
2073 static_cast<std::int64_t>(upper_raw);
2074 const std::int64_t value = as_i64(stack_[index_at++]);
2075 if(value < lower || value > upper) {
2076 return latch(ScanError::range_violation);
2077 }
2078 const std::uint64_t delta =
2079 static_cast<std::uint64_t>(value - lower) * stride;
2080 if(delta > std::numeric_limits<std::uint32_t>::max() -
2081 destination) {
2082 return latch(ScanError::invalid_bytecode);
2083 }
2084 destination += static_cast<std::uint32_t>(delta);
2085 }
2086 if(source_type != destination_type) {
2087 return latch(ScanError::invalid_bytecode);
2088 }
2089 const TypeDesc *desc = program_->types.get(destination_type);
2090 if(desc == nullptr || desc->size == 0 ||
2091 source > program_->vars_bytes ||
2092 desc->size > program_->vars_bytes - source ||
2093 destination > program_->vars_bytes ||
2094 desc->size > program_->vars_bytes - destination) {
2095 return latch(ScanError::invalid_bytecode);
2096 }
2097 sources[item] = source;
2098 destinations[item] = destination;
2099 bytes[item] = static_cast<std::uint32_t>(desc->size);
2100 for(std::uint16_t prior = 0; prior < item; ++prior) {
2101 const std::uint64_t prior_end =
2102 static_cast<std::uint64_t>(destinations[prior]) +
2103 bytes[prior];
2104 const std::uint64_t current_end =
2105 static_cast<std::uint64_t>(destination) +
2106 bytes[item];
2107 if(destination < prior_end &&
2108 destinations[prior] < current_end) {
2109 return latch(ScanError::alias_violation);
2110 }
2111 }
2112 }
2113 if(index_at != sp) {
2114 return latch(ScanError::invalid_bytecode);
2115 }
2116 for(std::uint16_t item = 0; item < count; ++item) {
2117 std::memmove(execution_vars_ + destinations[item],
2118 execution_vars_ + sources[item], bytes[item]);
2119 }
2120 sp = index_base;
2121 break;
2122 }
2123 case Op::alias_guard:
2124 if(sp < 1) {
2125 return latch(ScanError::invalid_bytecode);
2126 }
2127 if(stack_[sp - 1] == 0) {
2128 return latch(ScanError::alias_violation);
2129 }
2130 break;
2131 case Op::string_length: {
2132 if(pc >= size || sp >= stack_limit) {
2133 return latch(ScanError::invalid_bytecode);
2134 }
2135 const std::uint8_t constant = code[pc++];
2136 std::uint32_t offset = 0;
2137 std::uint32_t id = 0;
2138 if(!rd32(code, size, pc, offset) ||
2139 !rd32(code, size, pc, id)) {
2140 return latch(ScanError::invalid_bytecode);
2141 }
2142 const TypeDesc *desc = program_->types.get(id);
2143 if(desc == nullptr || (desc->kind != TypeKind::string &&
2144 desc->kind != TypeKind::wstring)) {
2145 return latch(ScanError::invalid_bytecode);
2146 }
2147 const unsigned char *object = nullptr;
2148 if(constant != 0) {
2149 if(offset > program_->string_constants.size() ||
2150 desc->size > program_->string_constants.size() - offset) {
2151 return latch(ScanError::invalid_bytecode);
2152 }
2153 object = program_->string_constants.data() + offset;
2154 } else {
2155 if(offset > program_->vars_bytes ||
2156 desc->size > program_->vars_bytes - offset) {
2157 return latch(ScanError::invalid_bytecode);
2158 }
2159 object = execution_vars_ + offset;
2160 }
2161 if(!valid_string_object(object, *desc) ||
2162 !charge_operation(read_le32(object))) {
2163 return latch(valid_string_object(object, *desc)
2166 }
2167 stack_[sp++] = read_le32(object);
2168 break;
2169 }
2170 case Op::standard_scalar: {
2171 if(pc + 3U > size) return latch(ScanError::invalid_bytecode);
2172 const StandardFunction function =
2173 static_cast<StandardFunction>(code[pc++]);
2174 const std::uint8_t argc = code[pc++];
2175 const Type type = static_cast<Type>(code[pc++]);
2176 if(argc == 0 || sp < argc ||
2177 function >= StandardFunction::count) {
2178 return latch(ScanError::invalid_bytecode);
2179 }
2180 if(!charge_operation(argc)) {
2181 return latch(ScanError::budget_exceeded);
2182 }
2183 const int base = sp - argc;
2184 const bool floating = is_real_family(type);
2185 auto real = [this](std::uint64_t raw) {
2186 return detail::bits_double(raw);
2187 };
2188 auto put_real = [this, type](double value) {
2189 if(type == Type::real) value = static_cast<float>(value);
2190 return detail::double_bits(value);
2191 };
2192 auto less = [floating, &real, type](std::uint64_t a,
2193 std::uint64_t b) {
2194 if(floating) return real(a) < real(b);
2195 if(is_unsigned_int(type) || is_bitstring(type)) return a < b;
2196 return static_cast<std::int64_t>(a) <
2197 static_cast<std::int64_t>(b);
2198 };
2199 auto equal = [floating, &real](std::uint64_t a,
2200 std::uint64_t b) {
2201 return floating ? real(a) == real(b) : a == b;
2202 };
2203 std::uint64_t value = stack_[base];
2204 if(function <= StandardFunction::atan) {
2205 if(function == StandardFunction::abs) {
2206 if(floating) value = put_real(std::fabs(real(value)));
2207 else if(static_cast<std::int64_t>(value) < 0)
2208 value = detail::canon(type, 0U - value);
2209 } else {
2210 const double x = real(value);
2211 double y = x;
2212 switch(function) {
2213 case StandardFunction::sqrt: y = std::sqrt(x); break;
2214 case StandardFunction::ln: y = std::log(x); break;
2215 case StandardFunction::log: y = std::log10(x); break;
2216 case StandardFunction::exp: y = std::exp(x); break;
2217 case StandardFunction::sin: y = std::sin(x); break;
2218 case StandardFunction::cos: y = std::cos(x); break;
2219 case StandardFunction::tan: y = std::tan(x); break;
2220 case StandardFunction::asin: y = std::asin(x); break;
2221 case StandardFunction::acos: y = std::acos(x); break;
2222 case StandardFunction::atan: y = std::atan(x); break;
2223 default: break;
2224 }
2225 value = put_real(y);
2226 }
2227 } else if(function >= StandardFunction::add &&
2228 function <= StandardFunction::max) {
2229 if(function == StandardFunction::expt) {
2230 value = put_real(std::pow(real(stack_[base]),
2231 real(stack_[base + 1])));
2232 } else if(function == StandardFunction::min ||
2233 function == StandardFunction::max) {
2234 for(int i = base + 1; i < sp; ++i) {
2235 const bool take = function == StandardFunction::min
2236 ? less(stack_[i], value) : less(value, stack_[i]);
2237 if(take) value = stack_[i];
2238 }
2239 } else if(floating) {
2240 double y = real(value);
2241 if(function == StandardFunction::add ||
2242 function == StandardFunction::mul) {
2243 for(int i = base + 1; i < sp; ++i)
2244 y = function == StandardFunction::add
2245 ? y + real(stack_[i]) : y * real(stack_[i]);
2246 } else {
2247 const double rhs = real(stack_[base + 1]);
2248 y = function == StandardFunction::sub ? y - rhs
2249 : function == StandardFunction::div ? y / rhs
2250 : std::fmod(y, rhs);
2251 }
2252 value = put_real(y);
2253 } else {
2254 auto apply = [type](std::uint64_t a, std::uint64_t b,
2255 StandardFunction op) {
2256 if(op == StandardFunction::add) return detail::canon(type, a + b);
2257 if(op == StandardFunction::sub) return detail::canon(type, a - b);
2258 if(op == StandardFunction::mul) return detail::canon(type, a * b);
2259 if(is_unsigned_int(type)) {
2260 return detail::canon(type,
2261 op == StandardFunction::div ? a / b : a % b);
2262 }
2263 const std::int64_t x = static_cast<std::int64_t>(a);
2264 const std::int64_t y = static_cast<std::int64_t>(b);
2265 if(x == std::numeric_limits<std::int64_t>::min() && y == -1)
2266 return detail::canon(type,
2267 op == StandardFunction::div ? a : 0U);
2268 return detail::canon(type, static_cast<std::uint64_t>(op == StandardFunction::div ? x / y : x % y));
2269 };
2270 if((function == StandardFunction::div || function == StandardFunction::mod) && stack_[base + 1] == 0)
2271 return latch(ScanError::division_by_zero);
2272 for(int i = base + 1; i < sp; ++i)
2273 value = apply(value, stack_[i], function);
2274 }
2275 } else if(function == StandardFunction::limit) {
2276 if(less(stack_[base + 2], stack_[base]))
2277 return latch(ScanError::invalid_argument);
2278 value = less(stack_[base + 1], stack_[base]) ? stack_[base]
2279 : less(stack_[base + 2], stack_[base + 1])
2280 ? stack_[base + 2] : stack_[base + 1];
2281 } else if(function == StandardFunction::sel) {
2282 value = stack_[base] ? stack_[base + 2] : stack_[base + 1];
2283 } else if(function == StandardFunction::mux) {
2284 const std::int64_t index = static_cast<std::int64_t>(stack_[base]);
2285 if(index < 0 || index >= argc - 1)
2286 return latch(ScanError::range_violation);
2287 value = stack_[base + 1 + static_cast<int>(index)];
2288 } else if(function >= StandardFunction::gt &&
2289 function <= StandardFunction::ne) {
2290 bool result = true;
2291 for(int i = base; i + 1 < sp && result; ++i) {
2292 const bool lt = less(stack_[i], stack_[i + 1]);
2293 const bool eq = equal(stack_[i], stack_[i + 1]);
2294 switch(function) {
2295 case StandardFunction::gt: result = !lt && !eq; break;
2296 case StandardFunction::ge: result = !lt; break;
2297 case StandardFunction::eq: result = eq; break;
2298 case StandardFunction::le: result = lt || eq; break;
2299 case StandardFunction::lt: result = lt; break;
2300 case StandardFunction::ne: result = !eq; break;
2301 default: break;
2302 }
2303 }
2304 value = result ? 1U : 0U;
2305 } else if(function >= StandardFunction::shl &&
2306 function <= StandardFunction::ror) {
2307 const std::int64_t count = static_cast<std::int64_t>(stack_[base + 1]);
2308 if(count < 0) return latch(ScanError::range_violation);
2309 const unsigned width = static_cast<unsigned>(width_bits(type));
2310 const std::uint64_t mask = width == 64 ? ~0ULL : ((1ULL << width) - 1U);
2311 const std::uint64_t input = stack_[base] & mask;
2312 if(function == StandardFunction::shl || function == StandardFunction::shr) {
2313 value = static_cast<std::uint64_t>(count) >= width ? 0U
2314 : function == StandardFunction::shl
2315 ? (input << count) & mask : input >> count;
2316 } else {
2317 const unsigned rotate = static_cast<unsigned>(count % width);
2318 value = rotate == 0 ? input
2319 : function == StandardFunction::rol
2320 ? ((input << rotate) | (input >> (width - rotate))) & mask
2321 : ((input >> rotate) | (input << (width - rotate))) & mask;
2322 }
2323 } else {
2324 constexpr std::int64_t day = 86400000000000LL;
2325 const std::int64_t a = static_cast<std::int64_t>(stack_[base]);
2326 const std::int64_t b = static_cast<std::int64_t>(stack_[base + 1]);
2327 std::int64_t out = 0;
2328 auto add_overflow = [](std::int64_t x, std::int64_t y, std::int64_t &z) {
2329 if((y > 0 && x > std::numeric_limits<std::int64_t>::max() - y) ||
2330 (y < 0 && x < std::numeric_limits<std::int64_t>::min() - y)) return true;
2331 z = x + y; return false;
2332 };
2333 auto sub_overflow = [](std::int64_t x, std::int64_t y,
2334 std::int64_t &z) {
2335 if((y > 0 && x < std::numeric_limits<std::int64_t>::min() + y) ||
2336 (y < 0 && x > std::numeric_limits<std::int64_t>::max() + y)) return true;
2337 z = x - y; return false;
2338 };
2339 auto mul_overflow = [](std::int64_t x, std::int64_t y,
2340 std::int64_t &z) {
2341 if(x == 0 || y == 0) { z = 0; return false; }
2342 if((x == -1 && y == std::numeric_limits<std::int64_t>::min()) ||
2343 (y == -1 && x == std::numeric_limits<std::int64_t>::min())) return true;
2344 if(x > 0) {
2345 if((y > 0 && x > std::numeric_limits<std::int64_t>::max() / y) ||
2346 (y < 0 && y < std::numeric_limits<std::int64_t>::min() / x)) return true;
2347 } else {
2348 if((y > 0 && x < std::numeric_limits<std::int64_t>::min() / y) ||
2349 (y < 0 && x < std::numeric_limits<std::int64_t>::max() / y)) return true;
2350 }
2351 z = x * y; return false;
2352 };
2353 switch(function) {
2356 if(add_overflow(a, b, out)) return latch(ScanError::date_time_range_violation);
2357 break;
2360 if(sub_overflow(a, b, out))
2362 break;
2364 out = ((a + b % day) % day + day) % day; break;
2366 out = ((a - b % day) % day + day) % day; break;
2368 { std::int64_t days = 0;
2369 if(sub_overflow(a, b, days) || mul_overflow(days, day, out))
2371 break;
2373 if(mul_overflow(a, b, out))
2375 break;
2377 if(b == 0) return latch(ScanError::division_by_zero);
2378 if(a == std::numeric_limits<std::int64_t>::min() && b == -1)
2380 out = a / b; break;
2382 { std::int64_t date_ns = 0;
2383 if(mul_overflow(a, day, date_ns) ||
2384 add_overflow(date_ns, b, out))
2386 break;
2387 default: return latch(ScanError::invalid_bytecode);
2388 }
2389 value = static_cast<std::uint64_t>(out);
2390 }
2391 stack_[base] = value;
2392 sp = base + 1;
2393 break;
2394 }
2395 case Op::standard_string: {
2396 if(pc + 10U > size) return latch(ScanError::invalid_bytecode);
2397 const StandardFunction function = static_cast<StandardFunction>(code[pc++]);
2398 const std::uint8_t argc = code[pc++];
2399 std::uint32_t destination = 0;
2400 std::uint32_t destination_id = 0;
2401 if(argc == 0 || argc > 32 || !rd32(code, size, pc, destination) ||
2402 !rd32(code, size, pc, destination_id))
2403 return latch(ScanError::invalid_bytecode);
2404 const unsigned char *objects[32] = {};
2405 const TypeDesc *descs[32] = {};
2406 bool string_arg[32] = {};
2407 int scalar_count = 0;
2408 std::uint32_t capacities[32] = {};
2409 std::uint8_t string_count = 0;
2410 for(std::uint8_t i = 0; i < argc; ++i) {
2411 if(pc >= size) return latch(ScanError::invalid_bytecode);
2412 string_arg[i] = code[pc++] != 0;
2413 if(!string_arg[i]) { ++scalar_count; continue; }
2414 if(pc >= size) return latch(ScanError::invalid_bytecode);
2415 const bool constant = code[pc++] != 0;
2416 std::uint32_t offset = 0, id = 0;
2417 if(!rd32(code, size, pc, offset) || !rd32(code, size, pc, id))
2418 return latch(ScanError::invalid_bytecode);
2419 descs[i] = program_->types.get(id);
2420 if(descs[i] == nullptr ||
2421 (descs[i]->kind != TypeKind::string && descs[i]->kind != TypeKind::wstring))
2422 return latch(ScanError::invalid_bytecode);
2423 capacities[string_count++] = static_cast<std::uint32_t>(
2424 descs[i]->string.capacity);
2425 if(constant) {
2426 if(offset > program_->string_constants.size() ||
2427 4U > program_->string_constants.size() - offset)
2428 return latch(ScanError::invalid_bytecode);
2429 objects[i] = program_->string_constants.data() + offset;
2430 const std::uint32_t units = read_le32(objects[i]);
2431 const std::uint64_t bytes = 4U + static_cast<std::uint64_t>(units) *
2432 (descs[i]->kind == TypeKind::wstring ? 4U : 1U);
2433 if(bytes > program_->string_constants.size() - offset)
2434 return latch(ScanError::invalid_bytecode);
2435 } else {
2436 if(offset > program_->vars_bytes || descs[i]->size > program_->vars_bytes - offset)
2437 return latch(ScanError::invalid_bytecode);
2438 objects[i] = execution_vars_ + offset;
2439 }
2440 if(!valid_string_object(objects[i], *descs[i]))
2441 return latch(ScanError::invalid_bytecode);
2442 }
2443 const auto valid_signature = [&]() {
2444 const auto string_at = [&](std::uint8_t index) {
2445 return index < argc && string_arg[index];
2446 };
2447 const auto scalar_at = [&](std::uint8_t index) {
2448 return index < argc && !string_arg[index];
2449 };
2450 switch(function) {
2452 return argc == 1U && string_at(0);
2455 return argc == 2U && string_at(0) && scalar_at(1);
2458 return argc == 3U && string_at(0) && scalar_at(1) &&
2459 scalar_at(2);
2461 if(argc < 2U) return false;
2462 for(std::uint8_t i = 0; i < argc; ++i)
2463 if(!string_at(i)) return false;
2464 return true;
2466 return argc == 3U && string_at(0) && string_at(1) &&
2467 scalar_at(2);
2469 return argc == 4U && string_at(0) && string_at(1) &&
2470 scalar_at(2) && scalar_at(3);
2472 return argc == 2U && string_at(0) && string_at(1);
2473 default:
2474 return false;
2475 }
2476 };
2477 const bool scalar_result = function == StandardFunction::len ||
2478 function == StandardFunction::find;
2479 if(!valid_signature() ||
2480 scalar_result !=
2481 (destination == std::numeric_limits<std::uint32_t>::max()))
2482 return latch(ScanError::invalid_bytecode);
2483 for(std::uint8_t i = 0; i < argc; ++i) {
2484 if(string_arg[i] && (objects[i] == nullptr || descs[i] == nullptr))
2485 return latch(ScanError::invalid_bytecode);
2486 }
2487 const TypeDesc *destination_desc =
2488 destination == std::numeric_limits<std::uint32_t>::max()
2489 ? nullptr : program_->types.get(destination_id);
2490 if(destination != std::numeric_limits<std::uint32_t>::max() &&
2491 (destination_desc == nullptr ||
2492 (destination_desc->kind != TypeKind::string &&
2493 destination_desc->kind != TypeKind::wstring))) {
2494 return latch(ScanError::invalid_bytecode);
2495 }
2496 const std::uint32_t destination_capacity =
2497 destination_desc == nullptr ? 0U
2498 : static_cast<std::uint32_t>(
2499 destination_desc->string.capacity);
2500 const std::uint32_t operation_cost = standard_string_cost(
2501 function, capacities, string_count, destination_capacity);
2502 if(sp < scalar_count || !charge_operation(operation_cost))
2503 return latch(sp < scalar_count ? ScanError::invalid_bytecode
2505 const int scalar_base = sp - scalar_count;
2506 int scalar_at = 0;
2507 auto scalar = [&](std::uint8_t argument) -> std::int64_t {
2508 int at = 0;
2509 for(std::uint8_t i = 0; i < argument; ++i)
2510 if(!string_arg[i]) ++at;
2511 return static_cast<std::int64_t>(stack_[scalar_base + at]);
2512 };
2513 auto scalar_length = [&](const unsigned char *object,
2514 const TypeDesc &desc) {
2515 if(desc.kind == TypeKind::wstring) return read_le32(object);
2516 const std::uint32_t bytes = read_le32(object);
2517 std::uint32_t at = 0, count = 0, codepoint = 0;
2518 while(at < bytes && next_utf8(object + 4U, bytes, at, codepoint)) ++count;
2519 return count;
2520 };
2521 auto unit_at = [&](const unsigned char *object, const TypeDesc &desc,
2522 std::uint32_t scalar_index) {
2523 if(desc.kind == TypeKind::wstring) return scalar_index * 4U;
2524 const std::uint32_t bytes = read_le32(object);
2525 std::uint32_t at = 0, count = 0, codepoint = 0;
2526 while(count < scalar_index && at < bytes) {
2527 next_utf8(object + 4U, bytes, at, codepoint); ++count;
2528 }
2529 return at;
2530 };
2531 if(function == StandardFunction::len || function == StandardFunction::find) {
2532 std::int64_t answer = 0;
2533 if(function == StandardFunction::len) {
2534 answer = scalar_length(objects[0], *descs[0]);
2535 } else {
2536 const std::uint32_t hay_units = read_le32(objects[0]);
2537 const std::uint32_t needle_units = read_le32(objects[1]);
2538 answer = needle_units == 0 ? 1 : 0;
2539 const std::uint32_t width =
2540 descs[0]->kind == TypeKind::wstring ? 4U : 1U;
2541 for(std::uint32_t pos = 0;
2542 answer == 0 && pos + needle_units <= hay_units;
2543 ++pos) {
2544 bool match = true;
2545 for(std::uint32_t unit = 0;
2546 unit < needle_units && match; ++unit) {
2547 const std::uint32_t hay_value = width == 4U
2548 ? read_le32(objects[0] + 4U +
2549 (static_cast<std::size_t>(pos) +
2550 unit) * 4U)
2551 : objects[0][4U + pos + unit];
2552 const std::uint32_t needle_value = width == 4U
2553 ? read_le32(objects[1] + 4U +
2554 static_cast<std::size_t>(unit) *
2555 4U)
2556 : objects[1][4U + unit];
2557 match = hay_value == needle_value;
2558 }
2559 if(match) {
2560 if(width == 4U) {
2561 answer = static_cast<std::int64_t>(pos) + 1;
2562 } else {
2563 std::uint32_t byte = 0, scalar_pos = 0,
2564 codepoint = 0;
2565 while(byte < pos && next_utf8(
2566 objects[0] + 4U, hay_units, byte,
2567 codepoint)) ++scalar_pos;
2568 answer =
2569 static_cast<std::int64_t>(scalar_pos) + 1;
2570 }
2571 }
2572 }
2573 }
2574 sp = scalar_base;
2575 if(sp >= stack_limit) return latch(ScanError::invalid_bytecode);
2576 stack_[sp++] = static_cast<std::uint64_t>(answer);
2577 break;
2578 }
2579 const TypeDesc *dst = destination_desc;
2580 if(dst == nullptr || destination == std::numeric_limits<std::uint32_t>::max() ||
2581 destination > program_->vars_bytes || dst->size > program_->vars_bytes - destination)
2582 return latch(ScanError::invalid_bytecode);
2583 std::array<unsigned char, 16388> output{};
2584 std::uint32_t output_units = 0;
2585 bool capacity_exceeded = false;
2586 const std::uint32_t destination_width =
2587 dst->kind == TypeKind::wstring ? 4U : 1U;
2588 const std::uint32_t destination_bytes =
2589 static_cast<std::uint32_t>(dst->string.capacity) *
2590 destination_width;
2591 auto append = [&](const unsigned char *object, const TypeDesc &desc,
2592 std::uint32_t first, std::uint32_t last) {
2593 const std::uint32_t begin = unit_at(object, desc, first);
2594 const std::uint32_t end = unit_at(object, desc, last);
2595 const std::uint32_t bytes = end - begin;
2596 if(bytes > destination_bytes - output_units ||
2597 4U + output_units + bytes > output.size()) {
2598 capacity_exceeded = true;
2599 return false;
2600 }
2601 std::memcpy(output.data() + 4U + output_units, object + 4U + begin, bytes);
2602 output_units += bytes;
2603 return true;
2604 };
2605 const std::uint32_t source_length = scalar_length(objects[0], *descs[0]);
2606 bool valid = true;
2607 switch(function) {
2609 for(std::uint8_t i = 0; i < argc && valid; ++i)
2610 valid = append(objects[i], *descs[i], 0, scalar_length(objects[i], *descs[i]));
2611 break;
2613 const std::int64_t count = scalar(1);
2614 if(count < 0) valid = false;
2615 else valid = append(objects[0], *descs[0], 0,
2616 std::min<std::uint32_t>(source_length, static_cast<std::uint32_t>(count)));
2617 break;
2618 }
2620 const std::int64_t count = scalar(1);
2621 if(count < 0) valid = false;
2622 else { const std::uint32_t take = std::min<std::uint32_t>(source_length, static_cast<std::uint32_t>(count));
2623 valid = append(objects[0], *descs[0], source_length - take, source_length); }
2624 break;
2625 }
2626 case StandardFunction::mid: {
2627 const std::int64_t count = scalar(1), position = scalar(2);
2628 if(count < 0 || position < 1 || position > static_cast<std::int64_t>(source_length) + 1) valid = false;
2629 else { const std::uint32_t begin = static_cast<std::uint32_t>(position - 1);
2630 valid = append(objects[0], *descs[0], begin,
2631 std::min<std::uint32_t>(source_length, begin + static_cast<std::uint32_t>(count))); }
2632 break;
2633 }
2635 const std::int64_t position = scalar(2);
2636 if(position < 1 || position > static_cast<std::int64_t>(source_length) + 1) valid = false;
2637 else { const std::uint32_t at = static_cast<std::uint32_t>(position - 1);
2638 valid = append(objects[0], *descs[0], 0, at) &&
2639 append(objects[1], *descs[1], 0, scalar_length(objects[1], *descs[1])) &&
2640 append(objects[0], *descs[0], at, source_length); }
2641 break;
2642 }
2644 const std::int64_t count = scalar(1), position = scalar(2);
2645 if(count < 0 || position < 1 || position > static_cast<std::int64_t>(source_length) + 1) valid = false;
2646 else { const std::uint32_t at = static_cast<std::uint32_t>(position - 1);
2647 const std::uint32_t end = std::min<std::uint32_t>(source_length, at + static_cast<std::uint32_t>(count));
2648 valid = append(objects[0], *descs[0], 0, at) && append(objects[0], *descs[0], end, source_length); }
2649 break;
2650 }
2652 const std::int64_t count = scalar(2), position = scalar(3);
2653 if(count < 0 || position < 1 || position > static_cast<std::int64_t>(source_length) + 1) valid = false;
2654 else { const std::uint32_t at = static_cast<std::uint32_t>(position - 1);
2655 const std::uint32_t end = std::min<std::uint32_t>(source_length, at + static_cast<std::uint32_t>(count));
2656 valid = append(objects[0], *descs[0], 0, at) &&
2657 append(objects[1], *descs[1], 0, scalar_length(objects[1], *descs[1])) &&
2658 append(objects[0], *descs[0], end, source_length); }
2659 break;
2660 }
2661 default: return latch(ScanError::invalid_bytecode);
2662 }
2663 if(!valid) return latch(capacity_exceeded
2666 const std::uint32_t width = destination_width;
2667 const std::uint32_t stored_units = width == 4U ? output_units / 4U : output_units;
2668 if(stored_units > dst->string.capacity)
2670 output[0] = static_cast<unsigned char>(stored_units);
2671 output[1] = static_cast<unsigned char>(stored_units >> 8U);
2672 output[2] = static_cast<unsigned char>(stored_units >> 16U);
2673 output[3] = static_cast<unsigned char>(stored_units >> 24U);
2674 std::memset(execution_vars_ + destination, 0, dst->size);
2675 std::memcpy(execution_vars_ + destination, output.data(),
2676 4U + output_units);
2677 sp = scalar_base;
2678 (void)scalar_at;
2679 break;
2680 }
2681
2682 default:
2683 return latch(ScanError::invalid_bytecode);
2684 }
2685 }
2686 }
2687
2688 // --- read-only symbol access (matrix 3.13; twin/monitoring ground) ----
2689
2690 std::size_t variable_count() const
2691 {
2692 return program_ ? program_->vars.size() : 0;
2693 }
2694
2695 const VarInfo *variable(std::size_t index) const
2696 {
2697 if(!program_ || index >= program_->vars.size()) {
2698 return nullptr;
2699 }
2700 return &program_->vars[index];
2701 }
2702
2703 // Case-insensitive lookup; returns -1 when absent.
2704 int find(const char *name) const
2705 {
2706 if(!program_ || name == nullptr) {
2707 return -1;
2708 }
2709 for(std::size_t i = 0; i < program_->vars.size(); ++i) {
2710 const char *lower = program_->vars[i].lower.c_str();
2711 std::size_t k = 0;
2712 bool match = true;
2713 for(; name[k] != '\0' && lower[k] != '\0'; ++k) {
2714 char c = name[k];
2715 if(c >= 'A' && c <= 'Z') {
2716 c = static_cast<char>(c - 'A' + 'a');
2717 }
2718 if(c != lower[k]) {
2719 match = false;
2720 break;
2721 }
2722 }
2723 if(match && name[k] == '\0' && lower[k] == '\0') {
2724 return static_cast<int>(i);
2725 }
2726 }
2727 return -1;
2728 }
2729
2730 std::int64_t value_i64(std::size_t index) const
2731 {
2732 if(!program_ || index >= program_->vars.size()) {
2733 return 0;
2734 }
2735 std::uint64_t value = 0;
2736 return load_value_at(visible_vars_, program_->vars[index].offset,
2737 program_->vars[index].type_id, value)
2738 ? as_i64(value)
2739 : 0;
2740 }
2741
2742 double value_f64(std::size_t index) const
2743 {
2744 if(!program_ || index >= program_->vars.size()) {
2745 return 0.0;
2746 }
2747 std::uint64_t value = 0;
2748 return load_value_at(visible_vars_, program_->vars[index].offset,
2749 program_->vars[index].type_id, value)
2750 ? detail::bits_double(value)
2751 : 0.0;
2752 }
2753
2754 bool value_bool(std::size_t index) const
2755 {
2756 return value_i64(index) != 0;
2757 }
2758
2759private:
2760 static constexpr std::uint32_t invalid_sfc_index =
2761 std::numeric_limits<std::uint32_t>::max();
2762 static constexpr std::size_t sfc_block_bytes = 16;
2763 static constexpr std::uint8_t action_direct = 1U;
2764 static constexpr std::uint8_t action_store = 2U;
2765 static constexpr std::uint8_t action_reset = 4U;
2766 static constexpr std::uint8_t action_expire = 8U;
2767
2768 unsigned char *sfc_at(std::uint32_t offset) const noexcept
2769 {
2770 return sfc_runtime_ + offset;
2771 }
2772
2773 bool sfc_commit_started() const noexcept
2774 {
2775 return sfc_runner_->phase == SfcRunnerPhase::commit_vars ||
2776 sfc_runner_->phase == SfcRunnerPhase::commit_active ||
2777 sfc_runner_->phase == SfcRunnerPhase::commit_blocks ||
2778 sfc_runner_->phase == SfcRunnerPhase::commit_actions ||
2779 sfc_runner_->phase == SfcRunnerPhase::finish;
2780 }
2781
2782 void rollback_sfc_commit() noexcept
2783 {
2784 if(program_ == nullptr || sfc_runtime_ == nullptr) return;
2785 std::memcpy(vars_, sfc_at(program_->sfc_committed_shadow_offset()),
2786 program_->vars_bytes);
2787 for(const SfcNetworkInfo &network : program_->sfc_networks) {
2788 std::memcpy(sfc_at(network.committed_active_offset),
2789 sfc_at(network.shadow_active_offset),
2790 network.steps.size());
2791 std::memcpy(sfc_at(network.committed_block_offset),
2792 sfc_at(network.shadow_block_offset),
2793 network.action_blocks.size() * sfc_block_bytes);
2794 std::memcpy(sfc_at(network.committed_action_offset),
2795 sfc_at(network.shadow_action_offset),
2796 network.actions.size());
2797 }
2798 }
2799
2800 static std::int64_t block_elapsed(const unsigned char *state) noexcept
2801 {
2802 std::int64_t result = 0;
2803 std::memcpy(&result, state, sizeof(result));
2804 return result;
2805 }
2806
2807 static void block_elapsed(unsigned char *state,
2808 std::int64_t value) noexcept
2809 {
2810 std::memcpy(state, &value, sizeof(value));
2811 }
2812
2813 static std::int64_t saturating_add(std::int64_t left,
2814 std::int64_t right) noexcept
2815 {
2816 if(right > 0 && left > std::numeric_limits<std::int64_t>::max() - right)
2817 return std::numeric_limits<std::int64_t>::max();
2818 return left + right;
2819 }
2820
2821 void reset_sfc_network(const SfcNetworkInfo &network) noexcept
2822 {
2823 std::memset(sfc_at(network.committed_active_offset), 0,
2824 network.steps.size());
2825 std::memset(sfc_at(network.staged_active_offset), 0,
2826 network.steps.size());
2827 std::memset(sfc_at(network.firing_offset), 0,
2828 network.transitions.size());
2829 std::memset(sfc_at(network.committed_block_offset), 0,
2830 network.action_blocks.size() * sfc_block_bytes);
2831 std::memset(sfc_at(network.staged_block_offset), 0,
2832 network.action_blocks.size() * sfc_block_bytes);
2833 std::memset(sfc_at(network.committed_action_offset), 0,
2834 network.actions.size());
2835 std::memset(sfc_at(network.staged_action_offset), 0,
2836 network.actions.size());
2837 std::memset(sfc_at(network.direct_action_offset), 0,
2838 network.actions.size());
2839 for(std::size_t index = 0; index < network.steps.size(); ++index) {
2840 if(!network.steps[index].initial) continue;
2841 sfc_at(network.committed_active_offset)[index] = 1U;
2842 sfc_at(network.staged_active_offset)[index] = 1U;
2843 }
2844 }
2845
2846 void initialize_sfc_runtime() noexcept
2847 {
2848 if(program_ == nullptr || sfc_runtime_ == nullptr ||
2849 program_->sfc_runtime_bytes == 0) return;
2850 std::memset(sfc_runtime_, 0, program_->sfc_runtime_bytes);
2851 for(const SfcNetworkInfo &network : program_->sfc_networks)
2852 reset_sfc_network(network);
2853 }
2854
2855 bool transition_eligible(const SfcNetworkInfo &network,
2856 std::size_t transition_index) const noexcept
2857 {
2858 const SfcTransitionInfo &transition =
2859 network.transitions[transition_index];
2860 if((transition.sources.size() > 1 || transition.targets.size() > 1) &&
2861 !transition.simultaneous) return false;
2862 const unsigned char *active =
2863 sfc_at(network.committed_active_offset);
2864 for(std::uint16_t source : transition.sources)
2865 if(source >= network.steps.size() || active[source] == 0)
2866 return false;
2867 const unsigned char *firing = sfc_at(network.firing_offset);
2868 for(std::size_t prior = 0; prior < transition_index; ++prior) {
2869 if(firing[prior] == 0) continue;
2870 for(std::uint16_t source : transition.sources) {
2871 if(std::find(network.transitions[prior].sources.begin(),
2872 network.transitions[prior].sources.end(),
2873 source) !=
2874 network.transitions[prior].sources.end()) return false;
2875 }
2876 }
2877 return true;
2878 }
2879
2880 void begin_sfc_regions() noexcept
2881 {
2882 sfc_runner_->phase = SfcRunnerPhase::stage_active;
2883 sfc_runner_->network_index = 0;
2884 sfc_runner_->item_index = 0;
2885 sfc_runner_->subitem_index = 0;
2886 sfc_runner_->active_region = nullptr;
2887 sfc_runner_->work_remaining = 0;
2888 sfc_runner_->reducer = 0;
2889 }
2890
2891 void finish_sfc_region() noexcept
2892 {
2893 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
2894 sfc_runner_->active_region = nullptr;
2895 return;
2896 }
2897 SfcNetworkInfo const &network =
2898 program_->sfc_networks[sfc_runner_->network_index];
2899 if(sfc_runner_->phase == SfcRunnerPhase::transitions &&
2900 sfc_runner_->item_index < network.transitions.size()) {
2901 const SfcRegionInfo &condition =
2902 network.transitions[sfc_runner_->item_index].condition;
2903 std::uint64_t raw = 0;
2904 if(load_value(condition.result_offset, type_id(Type::bool_), raw) &&
2905 raw != 0) {
2906 sfc_at(network.firing_offset)[sfc_runner_->item_index] = 1U;
2907 }
2908 }
2909 ++sfc_runner_->item_index;
2910 sfc_runner_->work_remaining = 0;
2911 sfc_runner_->active_region = nullptr;
2912 }
2913
2914 void update_sfc_qualifier_block(SfcNetworkInfo const &network,
2915 std::size_t index) noexcept
2916 {
2917 unsigned char *active = sfc_at(network.staged_active_offset);
2918 const unsigned char *old_active =
2919 sfc_at(network.committed_active_offset);
2920 const SfcActionBlockInfo &block = network.action_blocks[index];
2921 unsigned char *state = sfc_at(network.staged_block_offset) +
2922 index * sfc_block_bytes;
2923 const bool signal = block.step < network.steps.size() &&
2924 active[block.step] != 0;
2925 const bool activation = block.step < network.steps.size() &&
2926 (signal || old_active[block.step] != 0);
2927 const bool previous = state[9] != 0;
2928 const bool rising = activation && !previous;
2929 std::int64_t elapsed = block_elapsed(state);
2930 bool pending = state[8] != 0;
2931 bool latched = state[10] != 0;
2932 std::uint8_t contribution = 0;
2933 const SfcQualifier qualifier =
2934 static_cast<SfcQualifier>(block.qualifier);
2935 switch(qualifier) {
2936 case SfcQualifier::n:
2937 if(signal) contribution |= action_direct;
2938 break;
2939 case SfcQualifier::s:
2940 if(rising) latched = true;
2941 if(latched) contribution |= action_store;
2942 break;
2943 case SfcQualifier::r:
2944 if(signal) contribution |= action_reset;
2945 break;
2946 case SfcQualifier::p:
2947 if(rising) contribution |= action_direct;
2948 break;
2949 case SfcQualifier::l:
2950 if(!signal) {
2951 elapsed = 0;
2952 } else {
2953 elapsed = rising ? task_period_ns_ :
2954 saturating_add(elapsed, task_period_ns_);
2955 if(block.duration_ns > 0 &&
2956 elapsed <= block.duration_ns)
2957 contribution |= action_direct;
2958 }
2959 break;
2960 case SfcQualifier::d:
2961 if(!signal) {
2962 elapsed = 0;
2963 } else {
2964 elapsed = rising ? task_period_ns_ :
2965 saturating_add(elapsed, task_period_ns_);
2966 if(elapsed >= block.duration_ns)
2967 contribution |= action_direct;
2968 }
2969 break;
2970 case SfcQualifier::sd:
2971 if(rising && !latched) pending = true;
2972 if(pending) {
2973 elapsed = saturating_add(elapsed, task_period_ns_);
2974 if(elapsed >= block.duration_ns) {
2975 pending = false;
2976 latched = true;
2977 contribution |= action_store;
2978 }
2979 }
2980 if(latched) contribution |= action_store;
2981 break;
2982 case SfcQualifier::ds:
2983 if(!activation && !latched) {
2984 elapsed = 0;
2985 pending = false;
2986 } else if(activation && !latched) {
2987 pending = true;
2988 elapsed = rising ? task_period_ns_ :
2989 saturating_add(elapsed, task_period_ns_);
2990 if(elapsed >= block.duration_ns) {
2991 pending = false;
2992 latched = true;
2993 contribution |= action_store;
2994 }
2995 }
2996 if(latched) contribution |= action_store;
2997 break;
2998 case SfcQualifier::sl:
2999 if(rising) {
3000 latched = true;
3001 elapsed = task_period_ns_;
3002 contribution |= action_store;
3003 } else if(latched) {
3004 elapsed = saturating_add(elapsed, task_period_ns_);
3005 }
3006 if(latched && elapsed >= block.duration_ns) {
3007 latched = false;
3008 contribution |= action_expire;
3009 }
3010 if(latched) contribution |= action_store;
3011 break;
3012 }
3013 block_elapsed(state, elapsed);
3014 state[8] = pending ? 1U : 0U;
3015 state[9] = signal ? 1U : 0U;
3016 state[10] = latched ? 1U : 0U;
3017 state[11] = contribution;
3018 }
3019
3020 void start_sfc_phase(SfcRunnerPhase phase) noexcept
3021 {
3022 sfc_runner_->phase = phase;
3023 sfc_runner_->network_index = 0;
3024 sfc_runner_->item_index = 0;
3025 sfc_runner_->subitem_index = 0;
3026 sfc_runner_->work_remaining = 0;
3027 }
3028
3029 std::uint64_t transition_check_cost(
3030 const SfcNetworkInfo &network, std::size_t index) const noexcept
3031 {
3032 const SfcTransitionInfo &transition = network.transitions[index];
3033 std::uint64_t cost = 1U + transition.sources.size();
3034 for(std::size_t prior = 0; prior < index; ++prior)
3035 cost += 1U + transition.sources.size() *
3036 network.transitions[prior].sources.size();
3037 return cost;
3038 }
3039
3040 void advance_sfc_runner() noexcept
3041 {
3042 for(;;) {
3043 if(sfc_runner_->phase == SfcRunnerPhase::stage_vars) {
3044 if(sfc_runner_->item_index >= program_->vars_bytes) {
3045 visible_vars_ = sfc_at(
3046 program_->sfc_committed_shadow_offset());
3047 sfc_runner_->phase = SfcRunnerPhase::base;
3048 sfc_runner_->item_index = 0;
3049 sfc_runner_->subitem_index = 0;
3050 return;
3051 }
3052 if(sfc_runner_->subitem_index == 0) {
3053 sfc_runtime_[sfc_runner_->item_index] = vars_[sfc_runner_->item_index];
3054 sfc_runner_->subitem_index = 1;
3055 } else {
3056 sfc_at(program_->sfc_committed_shadow_offset())
3057 [sfc_runner_->item_index] = vars_[sfc_runner_->item_index];
3058 ++sfc_runner_->item_index;
3059 sfc_runner_->subitem_index = 0;
3060 if(sfc_runner_->item_index >= program_->vars_bytes) {
3061 visible_vars_ = sfc_at(
3062 program_->sfc_committed_shadow_offset());
3063 sfc_runner_->phase = SfcRunnerPhase::base;
3064 sfc_runner_->item_index = 0;
3065 }
3066 }
3067 return;
3068 }
3069 if(sfc_runner_->phase == SfcRunnerPhase::stage_active) {
3070 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3071 start_sfc_phase(SfcRunnerPhase::stage_firing);
3072 continue;
3073 }
3074 const SfcNetworkInfo &network =
3075 program_->sfc_networks[sfc_runner_->network_index];
3076 if(sfc_runner_->item_index >= network.steps.size()) {
3077 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3078 }
3079 if(sfc_runner_->subitem_index == 0) {
3080 sfc_at(network.staged_active_offset)[sfc_runner_->item_index] =
3081 sfc_at(network.committed_active_offset)[sfc_runner_->item_index];
3082 sfc_runner_->subitem_index = 1;
3083 } else {
3084 sfc_at(network.shadow_active_offset)[sfc_runner_->item_index] =
3085 sfc_at(network.committed_active_offset)[sfc_runner_->item_index];
3086 ++sfc_runner_->item_index;
3087 sfc_runner_->subitem_index = 0;
3088 }
3089 return;
3090 }
3091 if(sfc_runner_->phase == SfcRunnerPhase::stage_firing) {
3092 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3093 start_sfc_phase(SfcRunnerPhase::stage_blocks);
3094 continue;
3095 }
3096 const SfcNetworkInfo &network =
3097 program_->sfc_networks[sfc_runner_->network_index];
3098 if(sfc_runner_->item_index >= network.transitions.size()) {
3099 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3100 }
3101 sfc_at(network.firing_offset)[sfc_runner_->item_index++] = 0;
3102 return;
3103 }
3104 if(sfc_runner_->phase == SfcRunnerPhase::stage_blocks) {
3105 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3106 start_sfc_phase(SfcRunnerPhase::stage_actions);
3107 continue;
3108 }
3109 const SfcNetworkInfo &network =
3110 program_->sfc_networks[sfc_runner_->network_index];
3111 if(sfc_runner_->item_index >= network.action_blocks.size()) {
3112 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3113 }
3114 const std::size_t byte = sfc_runner_->subitem_index;
3115 const std::size_t offset =
3116 sfc_runner_->item_index * sfc_block_bytes + byte / 2U;
3117 if((byte & 1U) == 0)
3118 sfc_at(network.staged_block_offset)[offset] =
3119 sfc_at(network.committed_block_offset)[offset];
3120 else
3121 sfc_at(network.shadow_block_offset)[offset] =
3122 sfc_at(network.committed_block_offset)[offset];
3123 ++sfc_runner_->subitem_index;
3124 if(sfc_runner_->subitem_index == sfc_block_bytes * 2U) {
3125 ++sfc_runner_->item_index;
3126 sfc_runner_->subitem_index = 0;
3127 }
3128 return;
3129 }
3130 if(sfc_runner_->phase == SfcRunnerPhase::stage_actions ||
3131 sfc_runner_->phase == SfcRunnerPhase::stage_direct) {
3132 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3133 start_sfc_phase(sfc_runner_->phase == SfcRunnerPhase::stage_actions
3134 ? SfcRunnerPhase::stage_direct
3135 : SfcRunnerPhase::transitions);
3136 continue;
3137 }
3138 const SfcNetworkInfo &network =
3139 program_->sfc_networks[sfc_runner_->network_index];
3140 if(sfc_runner_->item_index >= network.actions.size()) {
3141 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3142 }
3143 if(sfc_runner_->phase == SfcRunnerPhase::stage_actions) {
3144 if(sfc_runner_->subitem_index == 0) {
3145 sfc_at(network.staged_action_offset)[sfc_runner_->item_index] =
3146 sfc_at(network.committed_action_offset)
3147 [sfc_runner_->item_index];
3148 sfc_runner_->subitem_index = 1;
3149 } else {
3150 sfc_at(network.shadow_action_offset)[sfc_runner_->item_index] =
3151 sfc_at(network.committed_action_offset)
3152 [sfc_runner_->item_index];
3153 ++sfc_runner_->item_index;
3154 sfc_runner_->subitem_index = 0;
3155 }
3156 } else {
3157 sfc_at(network.direct_action_offset)[sfc_runner_->item_index] = 0;
3158 ++sfc_runner_->item_index;
3159 }
3160 return;
3161 }
3162 if(sfc_runner_->phase == SfcRunnerPhase::transitions) {
3163 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3164 start_sfc_phase(SfcRunnerPhase::active_updates);
3165 continue;
3166 }
3167 const SfcNetworkInfo &network =
3168 program_->sfc_networks[sfc_runner_->network_index];
3169 if(sfc_runner_->item_index >= network.transitions.size()) {
3170 ++sfc_runner_->network_index; sfc_runner_->item_index = 0;
3171 sfc_runner_->work_remaining = 0; continue;
3172 }
3173 if(sfc_runner_->work_remaining == 0)
3174 sfc_runner_->work_remaining = transition_check_cost(
3175 network, sfc_runner_->item_index);
3176 if(--sfc_runner_->work_remaining != 0) return;
3177 if(transition_eligible(network, sfc_runner_->item_index)) {
3178 sfc_runner_->active_region =
3179 &network.transitions[sfc_runner_->item_index].condition;
3180 return;
3181 }
3182 ++sfc_runner_->item_index;
3183 return;
3184 }
3185 if(sfc_runner_->phase == SfcRunnerPhase::active_updates) {
3186 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3187 start_sfc_phase(SfcRunnerPhase::qualifier_blocks);
3188 continue;
3189 }
3190 const SfcNetworkInfo &network =
3191 program_->sfc_networks[sfc_runner_->network_index];
3192 if(sfc_runner_->item_index >= network.transitions.size()) {
3193 ++sfc_runner_->network_index; sfc_runner_->item_index = 0;
3194 sfc_runner_->subitem_index = 0; continue;
3195 }
3196 const SfcTransitionInfo &transition =
3197 network.transitions[sfc_runner_->item_index];
3198 const bool firing =
3199 sfc_at(network.firing_offset)[sfc_runner_->item_index] != 0;
3200 if(sfc_runner_->subitem_index == 0) {
3201 ++sfc_runner_->subitem_index;
3202 return;
3203 }
3204 if(sfc_runner_->subitem_index <= transition.sources.size()) {
3205 if(firing)
3206 sfc_at(network.staged_active_offset)
3207 [transition.sources[sfc_runner_->subitem_index - 1]] = 0;
3208 ++sfc_runner_->subitem_index;
3209 return;
3210 }
3211 const std::size_t target = sfc_runner_->subitem_index -
3212 transition.sources.size() - 1U;
3213 if(target < transition.targets.size()) {
3214 if(firing)
3215 sfc_at(network.staged_active_offset)
3216 [transition.targets[target]] = 1U;
3217 ++sfc_runner_->subitem_index;
3218 if(target + 1U < transition.targets.size()) return;
3219 }
3220 ++sfc_runner_->item_index;
3221 sfc_runner_->subitem_index = 0;
3222 return;
3223 }
3224 if(sfc_runner_->phase == SfcRunnerPhase::qualifier_blocks) {
3225 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3226 start_sfc_phase(SfcRunnerPhase::qualifier_actions);
3227 continue;
3228 }
3229 const SfcNetworkInfo &network =
3230 program_->sfc_networks[sfc_runner_->network_index];
3231 if(sfc_runner_->item_index >= network.action_blocks.size()) {
3232 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3233 }
3234 update_sfc_qualifier_block(network, sfc_runner_->item_index++);
3235 return;
3236 }
3237 if(sfc_runner_->phase == SfcRunnerPhase::qualifier_actions) {
3238 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3239 start_sfc_phase(SfcRunnerPhase::actions);
3240 continue;
3241 }
3242 const SfcNetworkInfo &network =
3243 program_->sfc_networks[sfc_runner_->network_index];
3244 if(sfc_runner_->item_index >= network.actions.size()) {
3245 ++sfc_runner_->network_index; sfc_runner_->item_index = 0;
3246 sfc_runner_->subitem_index = 0; continue;
3247 }
3248 const std::size_t blocks = network.action_blocks.size();
3249 if(sfc_runner_->subitem_index == 0) {
3250 sfc_runner_->reducer = 0;
3251 ++sfc_runner_->subitem_index;
3252 return;
3253 }
3254 if(sfc_runner_->subitem_index <= blocks) {
3255 const std::size_t block = sfc_runner_->subitem_index - 1U;
3256 if(network.action_blocks[block].action == sfc_runner_->item_index)
3257 sfc_runner_->reducer |=
3258 sfc_at(network.staged_block_offset)
3259 [block * sfc_block_bytes + 11U];
3260 ++sfc_runner_->subitem_index;
3261 return;
3262 }
3263 unsigned char *stored = sfc_at(network.staged_action_offset);
3264 if(sfc_runner_->subitem_index == blocks + 1U) {
3265 sfc_runner_->action_suppressed =
3266 (sfc_runner_->reducer & (action_reset | action_expire)) != 0;
3267 if((sfc_runner_->reducer & action_reset) != 0 ||
3268 (sfc_runner_->reducer & action_expire) != 0)
3269 stored[sfc_runner_->item_index] = 0;
3270 else if((sfc_runner_->reducer & action_store) != 0)
3271 stored[sfc_runner_->item_index] = 1U;
3272 ++sfc_runner_->subitem_index;
3273 return;
3274 }
3275 const std::size_t cleanup = sfc_runner_->subitem_index - blocks - 2U;
3276 if(cleanup < blocks) {
3277 if((sfc_runner_->reducer & action_reset) != 0 &&
3278 network.action_blocks[cleanup].action == sfc_runner_->item_index) {
3279 unsigned char *state =
3280 sfc_at(network.staged_block_offset) +
3281 cleanup * sfc_block_bytes;
3282 const unsigned char previous = state[9];
3283 std::memset(state, 0, sfc_block_bytes);
3284 state[9] = previous;
3285 }
3286 ++sfc_runner_->subitem_index;
3287 return;
3288 }
3289 sfc_at(network.direct_action_offset)[sfc_runner_->item_index] =
3290 !sfc_runner_->action_suppressed &&
3291 (stored[sfc_runner_->item_index] != 0 ||
3292 (sfc_runner_->reducer & action_direct) != 0)
3293 ? 1U : 0U;
3294 ++sfc_runner_->item_index;
3295 sfc_runner_->subitem_index = 0;
3296 return;
3297 }
3298 if(sfc_runner_->phase == SfcRunnerPhase::actions) {
3299 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3300 start_sfc_phase(SfcRunnerPhase::trace_exits);
3301 continue;
3302 }
3303 const SfcNetworkInfo &network =
3304 program_->sfc_networks[sfc_runner_->network_index];
3305 if(sfc_runner_->item_index >= network.actions.size()) {
3306 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3307 }
3308 if(sfc_at(network.direct_action_offset)[sfc_runner_->item_index] != 0) {
3309 sfc_runner_->active_region = &network.actions[sfc_runner_->item_index].region;
3310 return;
3311 }
3312 ++sfc_runner_->item_index;
3313 return;
3314 }
3315 break;
3316 }
3317 advance_sfc_trace_and_commit();
3318 }
3319
3320 void append_sfc_trace(std::size_t network_index, SfcEventKind kind,
3321 std::size_t entity_index, std::uint8_t qualifier,
3322 std::int32_t line, std::int32_t column,
3323 std::int32_t end_line,
3324 std::int32_t end_column) noexcept
3325 {
3326 if(sfc_runner_->trace_size >= sfc_runner_->trace_capacity) {
3327 ++sfc_runner_->trace_dropped;
3328 return;
3329 }
3330 SfcTraceRecord &record = sfc_runner_->trace[sfc_runner_->trace_size++];
3331 record = SfcTraceRecord{};
3332 record.scan = sfc_runner_->scan;
3333 record.network = static_cast<std::uint32_t>(network_index);
3334 record.kind = kind;
3335 record.qualifier = qualifier;
3336 record.line = line;
3337 record.column = column;
3338 record.end_line = end_line;
3339 record.end_column = end_column;
3340 const std::uint32_t index = static_cast<std::uint32_t>(entity_index);
3341 if(kind == SfcEventKind::step_exit ||
3342 kind == SfcEventKind::step_enter) record.step = index;
3343 else if(kind == SfcEventKind::transition_fire)
3344 record.transition = index;
3345 else if(kind == SfcEventKind::qualifier_update) record.block = index;
3346 else if(kind == SfcEventKind::action_execute) record.action = index;
3347 }
3348
3349 void advance_sfc_trace_and_commit() noexcept
3350 {
3351 for(;;) {
3352 if(sfc_runner_->phase == SfcRunnerPhase::commit_vars) {
3353 if(sfc_runner_->item_index < program_->vars_bytes) {
3354 vars_[sfc_runner_->item_index] = sfc_runtime_[sfc_runner_->item_index];
3355 ++sfc_runner_->item_index;
3356 return;
3357 }
3358 start_sfc_phase(SfcRunnerPhase::commit_active);
3359 continue;
3360 }
3361 if(sfc_runner_->network_index >= program_->sfc_networks.size()) {
3362 SfcRunnerPhase next = SfcRunnerPhase::finish;
3363 switch(sfc_runner_->phase) {
3364 case SfcRunnerPhase::trace_exits:
3365 next = SfcRunnerPhase::trace_transitions; break;
3366 case SfcRunnerPhase::trace_transitions:
3367 next = SfcRunnerPhase::trace_enters; break;
3368 case SfcRunnerPhase::trace_enters:
3369 next = SfcRunnerPhase::trace_qualifiers; break;
3370 case SfcRunnerPhase::trace_qualifiers:
3371 next = SfcRunnerPhase::trace_actions; break;
3372 case SfcRunnerPhase::trace_actions:
3373 next = SfcRunnerPhase::commit_vars; break;
3374 case SfcRunnerPhase::commit_active:
3375 next = SfcRunnerPhase::commit_blocks; break;
3376 case SfcRunnerPhase::commit_blocks:
3377 next = SfcRunnerPhase::commit_actions; break;
3378 case SfcRunnerPhase::commit_actions:
3379 next = SfcRunnerPhase::finish; break;
3380 default: break;
3381 }
3382 start_sfc_phase(next);
3383 continue;
3384 }
3385 const SfcNetworkInfo &network =
3386 program_->sfc_networks[sfc_runner_->network_index];
3387 const unsigned char *old_active =
3388 sfc_at(network.committed_active_offset);
3389 const unsigned char *new_active =
3390 sfc_at(network.staged_active_offset);
3391 if(sfc_runner_->phase == SfcRunnerPhase::trace_exits ||
3392 sfc_runner_->phase == SfcRunnerPhase::trace_enters) {
3393 if(sfc_runner_->item_index >= network.steps.size()) {
3394 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3395 }
3396 const std::size_t step = sfc_runner_->item_index++;
3397 const bool emit = sfc_runner_->phase == SfcRunnerPhase::trace_exits
3398 ? old_active[step] != 0 && new_active[step] == 0
3399 : old_active[step] == 0 && new_active[step] != 0;
3400 if(emit)
3401 append_sfc_trace(sfc_runner_->network_index,
3402 sfc_runner_->phase == SfcRunnerPhase::trace_exits
3403 ? SfcEventKind::step_exit
3404 : SfcEventKind::step_enter,
3405 step, 0, network.steps[step].line,
3406 network.steps[step].column,
3407 network.steps[step].end_line,
3408 network.steps[step].end_column);
3409 return;
3410 }
3411 if(sfc_runner_->phase == SfcRunnerPhase::trace_transitions) {
3412 if(sfc_runner_->item_index >= network.transitions.size()) {
3413 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3414 }
3415 const std::size_t transition = sfc_runner_->item_index++;
3416 if(sfc_at(network.firing_offset)[transition] != 0)
3417 append_sfc_trace(sfc_runner_->network_index,
3418 SfcEventKind::transition_fire,
3419 transition, 0,
3420 network.transitions[transition].line,
3421 network.transitions[transition].column,
3422 network.transitions[transition].end_line,
3423 network.transitions[transition].end_column);
3424 return;
3425 }
3426 if(sfc_runner_->phase == SfcRunnerPhase::trace_qualifiers) {
3427 if(sfc_runner_->item_index >= network.action_blocks.size()) {
3428 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3429 }
3430 const std::size_t block = sfc_runner_->item_index++;
3431 append_sfc_trace(sfc_runner_->network_index,
3432 SfcEventKind::qualifier_update, block,
3433 network.action_blocks[block].qualifier,
3434 network.action_blocks[block].line,
3435 network.action_blocks[block].column,
3436 network.action_blocks[block].end_line,
3437 network.action_blocks[block].end_column);
3438 return;
3439 }
3440 if(sfc_runner_->phase == SfcRunnerPhase::trace_actions) {
3441 if(sfc_runner_->item_index >= network.actions.size()) {
3442 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3443 }
3444 const std::size_t action = sfc_runner_->item_index++;
3445 const unsigned char *execute =
3446 sfc_at(network.direct_action_offset);
3447 if(execute[action] != 0)
3448 append_sfc_trace(sfc_runner_->network_index,
3449 SfcEventKind::action_execute, action, 0,
3450 network.actions[action].line,
3451 network.actions[action].column,
3452 network.actions[action].end_line,
3453 network.actions[action].end_column);
3454 return;
3455 }
3456 if(sfc_runner_->phase == SfcRunnerPhase::commit_active) {
3457 if(sfc_runner_->item_index >= network.steps.size()) {
3458 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3459 }
3460 sfc_at(network.committed_active_offset)[sfc_runner_->item_index] =
3461 sfc_at(network.staged_active_offset)[sfc_runner_->item_index];
3462 ++sfc_runner_->item_index;
3463 return;
3464 }
3465 if(sfc_runner_->phase == SfcRunnerPhase::commit_blocks) {
3466 if(sfc_runner_->item_index >= network.action_blocks.size()) {
3467 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3468 }
3469 const std::size_t offset =
3470 sfc_runner_->item_index * sfc_block_bytes + sfc_runner_->subitem_index;
3471 sfc_at(network.committed_block_offset)[offset] =
3472 sfc_at(network.staged_block_offset)[offset];
3473 ++sfc_runner_->subitem_index;
3474 if(sfc_runner_->subitem_index == sfc_block_bytes) {
3475 ++sfc_runner_->item_index;
3476 sfc_runner_->subitem_index = 0;
3477 }
3478 return;
3479 }
3480 if(sfc_runner_->phase == SfcRunnerPhase::commit_actions) {
3481 if(sfc_runner_->item_index >= network.actions.size()) {
3482 ++sfc_runner_->network_index; sfc_runner_->item_index = 0; continue;
3483 }
3484 sfc_at(network.committed_action_offset)[sfc_runner_->item_index] =
3485 sfc_at(network.staged_action_offset)[sfc_runner_->item_index];
3486 ++sfc_runner_->item_index;
3487 return;
3488 }
3489 if(sfc_runner_->phase == SfcRunnerPhase::finish) {
3490 execution_vars_ = vars_;
3491 visible_vars_ = vars_;
3492 ++sfc_runner_->scan;
3493 if(process_image_ != nullptr)
3494 process_image_->commit_scan(
3495 *program_, vars_, !defer_process_image_publish_);
3496 sfc_runner_->phase = SfcRunnerPhase::none;
3497 return;
3498 }
3499 }
3500 }
3501
3502 template <typename Storage>
3503 static Storage *construct_binding_storage(unsigned char *&cursor)
3504 {
3505 static_assert(alignof(Storage) <= 8U);
3506 Storage *storage = ::new(static_cast<void *>(cursor)) Storage{};
3507 cursor += sizeof(Storage);
3508 return storage;
3509 }
3510
3511 void load_binding_storage(const Program &program, unsigned char *cursor)
3512 {
3513 for(std::uint8_t value =
3514 static_cast<std::uint8_t>(BindingStorageKind::axis_targets);
3515 value <=
3516 static_cast<std::uint8_t>(BindingStorageKind::kin_transforms);
3517 ++value) {
3518 const BindingStorageKind kind =
3519 static_cast<BindingStorageKind>(value);
3520 if(!program.uses_binding_storage(kind)) continue;
3521 switch(kind) {
3522 case BindingStorageKind::axis_targets:
3523 axis_targets_ =
3524 construct_binding_storage<AxisTargetStorage>(cursor);
3525 break;
3526 case BindingStorageKind::group_targets:
3527 group_targets_ =
3528 construct_binding_storage<GroupTargetStorage>(cursor);
3529 break;
3530 case BindingStorageKind::path_tables:
3531 path_tables_ =
3532 construct_binding_storage<PathTableStorage>(cursor);
3533 break;
3534 case BindingStorageKind::path_descriptions:
3535 path_descriptions_ =
3536 construct_binding_storage<PathDescriptionStorage>(cursor);
3537 break;
3538 case BindingStorageKind::cam_switch_tables:
3539 cam_switch_tables_ =
3540 construct_binding_storage<CamSwitchTableStorage>(cursor);
3541 break;
3542 case BindingStorageKind::cam_switch_outputs:
3543 cam_switch_outputs_ =
3544 construct_binding_storage<CamSwitchOutputStorage>(cursor);
3545 break;
3546 case BindingStorageKind::cam_track_options:
3547 cam_track_options_ =
3548 construct_binding_storage<CamTrackOptionStorage>(cursor);
3549 break;
3550 case BindingStorageKind::cam_tables:
3551 cam_tables_ =
3552 construct_binding_storage<CamTableStorage>(cursor);
3553 break;
3554 case BindingStorageKind::position_profiles:
3555 position_profiles_ =
3556 construct_binding_storage<PositionProfileStorage>(cursor);
3557 break;
3558 case BindingStorageKind::velocity_profiles:
3559 velocity_profiles_ =
3560 construct_binding_storage<VelocityProfileStorage>(cursor);
3561 break;
3562 case BindingStorageKind::acceleration_profiles:
3563 acceleration_profiles_ = construct_binding_storage<
3565 break;
3566 case BindingStorageKind::kin_transforms:
3567 kin_transforms_ =
3568 construct_binding_storage<KinTransformStorage>(cursor);
3569 break;
3570 case BindingStorageKind::none: break;
3571 }
3572 }
3573 }
3574
3575 template <typename Register>
3576 BindingError bind_named_handle(const char *name, TypeId expected,
3577 std::size_t capacity,
3578 Register register_value)
3579 {
3580 if(program_ == nullptr || name == nullptr) return BindingError::unknown;
3581 if(scan_started_) return BindingError::locked;
3582 std::size_t slot = 0;
3583 for(const VarInfo &var : program_->vars) {
3584 if(var.type_id != expected) continue;
3585 if(!ascii_name_equal(name, var.lower)) {
3586 ++slot;
3587 continue;
3588 }
3589 if(slot >= capacity) return BindingError::capacity_exceeded;
3590 std::uint64_t handle = 0;
3591 std::memcpy(&handle, vars_ + var.offset, sizeof(handle));
3592 if(handle != 0U) return BindingError::duplicate;
3593 const BindingError result = register_value(slot);
3594 if(result != BindingError::ok) return result;
3595 handle = static_cast<std::uint64_t>(slot) + 1U;
3596 std::memcpy(vars_ + var.offset, &handle, sizeof(handle));
3597 return BindingError::ok;
3598 }
3599 return BindingError::unknown;
3600 }
3601
3602 template <std::size_t Capacity>
3603 BindingError bind_profile(const char *name, TypeId type,
3604 std::array<BindingProfileSlot, Capacity> &profiles,
3605 const BindingProfileSlot &decoded)
3606 {
3607 return bind_named_handle(
3608 name, type, profiles.size(), [&](std::size_t slot) {
3609 profiles[slot] = decoded;
3610 return BindingError::ok;
3611 });
3612 }
3613
3614 static BindingTargetKind reference_kind(Type type, TypeId type_id)
3615 {
3616 if(type == Type::axis_ref || type_id == binding_type::axis_ref ||
3617 type_id == binding_type::mc_input_ref ||
3618 type_id == binding_type::mc_output_ref) {
3619 return BindingTargetKind::axis;
3620 }
3621 if(type == Type::group_ref || type_id == binding_type::group_ref) {
3622 return BindingTargetKind::group;
3623 }
3624 return BindingTargetKind::invalid;
3625 }
3626
3627 template <typename Text>
3628 static bool ascii_name_equal(const char *name, const Text &lower)
3629 {
3630 std::size_t index = 0;
3631 while(name[index] != '\0' && index < lower.size()) {
3632 char value = name[index];
3633 if(value >= 'A' && value <= 'Z') {
3634 value = static_cast<char>(value - 'A' + 'a');
3635 }
3636 if(value != lower[index]) return false;
3637 ++index;
3638 }
3639 return index == lower.size() && name[index] == '\0';
3640 }
3641
3642 bool resolve_reference_payload(Type type, TypeId type_id,
3643 std::int64_t &value) const
3644 {
3645 const BindingTargetKind kind = reference_kind(type, type_id);
3646 if(kind == BindingTargetKind::invalid) return true;
3647 const std::uint64_t handle = static_cast<std::uint64_t>(value);
3648 if(handle == 0) {
3649 value = 0;
3650 return true;
3651 }
3652 const std::size_t slot = static_cast<std::size_t>(handle - 1U);
3653 void *target = nullptr;
3654 if(kind == BindingTargetKind::axis) {
3655 if(slot >= axis_targets_->size()) return false;
3656 target = (*axis_targets_)[slot];
3657 } else {
3658 if(slot >= group_targets_->size()) return false;
3659 target = (*group_targets_)[slot];
3660 }
3661 if(target == nullptr) return false;
3662 value = static_cast<std::int64_t>(
3663 reinterpret_cast<std::uintptr_t>(target));
3664 return true;
3665 }
3666
3667 bool encode_reference_payload(Type type, TypeId type_id,
3668 std::int64_t &value) const
3669 {
3670 const BindingTargetKind kind = reference_kind(type, type_id);
3671 if(kind == BindingTargetKind::invalid) return true;
3672 if(value == 0) return true;
3673 const std::uintptr_t target = static_cast<std::uintptr_t>(value);
3674 if(kind == BindingTargetKind::axis) {
3675 for(std::size_t slot = 0; slot < axis_targets_->size(); ++slot) {
3676 if(reinterpret_cast<std::uintptr_t>((*axis_targets_)[slot]) ==
3677 target) {
3678 value = static_cast<std::int64_t>(slot + 1U);
3679 return true;
3680 }
3681 }
3682 } else {
3683 for(std::size_t slot = 0; slot < group_targets_->size(); ++slot) {
3684 if(reinterpret_cast<std::uintptr_t>((*group_targets_)[slot]) ==
3685 target) {
3686 value = static_cast<std::int64_t>(slot + 1U);
3687 return true;
3688 }
3689 }
3690 }
3691 return false;
3692 }
3693
3694 bool resolve_sequence_payload(
3695 TypeId type, std::int64_t value,
3696 generated::StBindingNativeSequenceValue &sequence) const
3697 {
3698 if(value == 0) {
3699 sequence = {};
3700 return true;
3701 }
3702 if(value < 0) return false;
3703 const std::uint64_t handle = static_cast<std::uint64_t>(value);
3704 const std::size_t slot = static_cast<std::size_t>(handle - 1U);
3705 switch(type) {
3706 case binding_type::mc_path_table:
3707 if(slot >= path_tables_->size() ||
3708 (*path_tables_)[slot] == nullptr) {
3709 return false;
3710 }
3711 sequence = {(*path_tables_)[slot], 1U, false};
3712 return true;
3713 case binding_type::mc_path_description:
3714 if(slot >= path_descriptions_->size() ||
3715 (*path_descriptions_)[slot].count == 0U) {
3716 return false;
3717 }
3718 sequence = {&(*path_descriptions_)[slot], 1U, false};
3719 return true;
3720 case binding_type::mc_cam_switch_table_view:
3721 if(slot >= cam_switch_tables_->size() ||
3722 (*cam_switch_tables_)[slot].data == nullptr) {
3723 return false;
3724 }
3725 sequence = {(*cam_switch_tables_)[slot].data,
3726 (*cam_switch_tables_)[slot].size, false};
3727 return true;
3728 case binding_type::mc_cam_switch_outputs_view:
3729 if(slot >= cam_switch_outputs_->size() ||
3730 (*cam_switch_outputs_)[slot].data == nullptr) {
3731 return false;
3732 }
3733 sequence = {(*cam_switch_outputs_)[slot].data,
3734 (*cam_switch_outputs_)[slot].size, false};
3735 return true;
3736 case binding_type::mc_cam_track_options_view:
3737 if(slot >= cam_track_options_->size() ||
3738 (*cam_track_options_)[slot].data == nullptr) {
3739 return false;
3740 }
3741 sequence = {(*cam_track_options_)[slot].data,
3742 (*cam_track_options_)[slot].size, false};
3743 return true;
3744 case binding_type::mc_cam_table_view:
3745 if(slot >= cam_tables_->size() ||
3746 (*cam_tables_)[slot].points == nullptr) {
3747 return false;
3748 }
3749 sequence = {(*cam_tables_)[slot].points,
3750 (*cam_tables_)[slot].size,
3751 (*cam_tables_)[slot].periodic};
3752 return true;
3753 case binding_type::mc_time_position:
3754 return resolve_profile_payload(*position_profiles_, slot,
3755 sequence);
3756 case binding_type::mc_time_velocity:
3757 return resolve_profile_payload(*velocity_profiles_, slot,
3758 sequence);
3759 case binding_type::mc_time_acceleration:
3760 return resolve_profile_payload(*acceleration_profiles_, slot,
3761 sequence);
3762 default: return false;
3763 }
3764 }
3765
3766 bool resolve_tagged_reference_payload(
3767 TypeId type, std::int64_t value,
3768 generated::StBindingNativeTaggedReferenceValue &tagged) const
3769 {
3770 if(type != binding_type::mc_kin_transform_ref) return false;
3771 if(value == 0) {
3772 tagged = {};
3773 return true;
3774 }
3775 if(value < 0) return false;
3776 const std::size_t slot = static_cast<std::size_t>(
3777 static_cast<std::uint64_t>(value) - 1U);
3778 if(slot >= kin_transforms_->size()) return false;
3779 const axis::KinTransformRef &transform = (*kin_transforms_)[slot];
3780 switch(transform.kind) {
3781 case axis::KinTransformKind::kinematics:
3782 if(transform.kinematics == nullptr || transform.pose != nullptr) {
3783 return false;
3784 }
3785 tagged = {
3786 transform.kinematics,
3787 generated::StBindingNativeTaggedReferenceTag::kinematics};
3788 return true;
3789 case axis::KinTransformKind::pose:
3790 if(transform.pose == nullptr || transform.kinematics != nullptr) {
3791 return false;
3792 }
3793 tagged = {transform.pose,
3794 generated::StBindingNativeTaggedReferenceTag::pose};
3795 return true;
3796 case axis::KinTransformKind::none:
3797 default: return false;
3798 }
3799 }
3800
3801 bool encode_tagged_reference_payload(
3802 TypeId type,
3803 const generated::StBindingNativeTaggedReferenceValue &tagged,
3804 std::int64_t &handle) const
3805 {
3806 if(type != binding_type::mc_kin_transform_ref) return false;
3807 if(tagged.tag ==
3808 generated::StBindingNativeTaggedReferenceTag::none &&
3809 tagged.data == nullptr) {
3810 handle = 0;
3811 return true;
3812 }
3813 for(std::size_t slot = 0; slot < kin_transforms_->size(); ++slot) {
3814 const axis::KinTransformRef &transform = (*kin_transforms_)[slot];
3815 const bool matches =
3816 (tagged.tag ==
3817 generated::StBindingNativeTaggedReferenceTag::kinematics &&
3818 transform.kind == axis::KinTransformKind::kinematics &&
3819 transform.kinematics == tagged.data &&
3820 transform.pose == nullptr) ||
3821 (tagged.tag ==
3822 generated::StBindingNativeTaggedReferenceTag::pose &&
3823 transform.kind == axis::KinTransformKind::pose &&
3824 transform.pose == tagged.data &&
3825 transform.kinematics == nullptr);
3826 if(matches) {
3827 handle = static_cast<std::int64_t>(slot + 1U);
3828 return true;
3829 }
3830 }
3831 return false;
3832 }
3833
3834 bool encode_sequence_payload(
3835 TypeId type, const generated::StBindingNativeSequenceValue &sequence,
3836 std::int64_t &handle) const
3837 {
3838 if(sequence.data == nullptr && sequence.count == 0U &&
3839 !sequence.flag) {
3840 handle = 0;
3841 return true;
3842 }
3843 switch(type) {
3844 case binding_type::mc_path_table:
3845 if(sequence.count != 1U || sequence.flag) return false;
3846 return find_sequence_handle(*path_tables_, sequence.data, handle);
3847 case binding_type::mc_path_description:
3848 if(sequence.count != 1U || sequence.flag) return false;
3849 for(std::size_t slot = 0; slot < path_descriptions_->size();
3850 ++slot) {
3851 if((*path_descriptions_)[slot].count != 0U &&
3852 &(*path_descriptions_)[slot] == sequence.data) {
3853 handle = static_cast<std::int64_t>(slot + 1U);
3854 return true;
3855 }
3856 }
3857 return false;
3858 case binding_type::mc_cam_switch_table_view:
3859 if(sequence.flag) return false;
3860 for(std::size_t slot = 0; slot < cam_switch_tables_->size();
3861 ++slot) {
3862 const auto &view = (*cam_switch_tables_)[slot];
3863 if(view.data == sequence.data && view.size == sequence.count) {
3864 handle = static_cast<std::int64_t>(slot + 1U);
3865 return true;
3866 }
3867 }
3868 return false;
3869 case binding_type::mc_cam_switch_outputs_view:
3870 if(sequence.flag) return false;
3871 for(std::size_t slot = 0; slot < cam_switch_outputs_->size();
3872 ++slot) {
3873 const auto &view = (*cam_switch_outputs_)[slot];
3874 if(view.data == sequence.data &&
3875 view.size == sequence.count) {
3876 handle = static_cast<std::int64_t>(slot + 1U);
3877 return true;
3878 }
3879 }
3880 return false;
3881 case binding_type::mc_cam_track_options_view:
3882 if(sequence.flag) return false;
3883 for(std::size_t slot = 0; slot < cam_track_options_->size();
3884 ++slot) {
3885 const auto &view = (*cam_track_options_)[slot];
3886 if(view.data == sequence.data &&
3887 view.size == sequence.count) {
3888 handle = static_cast<std::int64_t>(slot + 1U);
3889 return true;
3890 }
3891 }
3892 return false;
3893 case binding_type::mc_cam_table_view:
3894 for(std::size_t slot = 0; slot < cam_tables_->size(); ++slot) {
3895 const auto &view = (*cam_tables_)[slot];
3896 if(view.points == sequence.data && view.size == sequence.count &&
3897 view.periodic == sequence.flag) {
3898 handle = static_cast<std::int64_t>(slot + 1U);
3899 return true;
3900 }
3901 }
3902 return false;
3903 case binding_type::mc_time_position:
3904 if(sequence.flag) return false;
3905 return find_profile_handle(*position_profiles_, sequence, handle);
3906 case binding_type::mc_time_velocity:
3907 if(sequence.flag) return false;
3908 return find_profile_handle(*velocity_profiles_, sequence, handle);
3909 case binding_type::mc_time_acceleration:
3910 if(sequence.flag) return false;
3911 return find_profile_handle(*acceleration_profiles_, sequence,
3912 handle);
3913 default: return false;
3914 }
3915 }
3916
3917 template <std::size_t Capacity>
3918 static bool resolve_profile_payload(
3919 const std::array<BindingProfileSlot, Capacity> &profiles,
3920 std::size_t slot,
3921 generated::StBindingNativeSequenceValue &sequence)
3922 {
3923 if(slot >= profiles.size() || profiles[slot].count == 0U) return false;
3924 sequence = {profiles[slot].segments.data(), profiles[slot].count,
3925 false};
3926 return true;
3927 }
3928
3929 template <typename Pointer, std::size_t Capacity>
3930 static bool find_sequence_handle(const std::array<Pointer, Capacity> &values,
3931 const void *data, std::int64_t &handle)
3932 {
3933 for(std::size_t slot = 0; slot < values.size(); ++slot) {
3934 if(values[slot] == data) {
3935 handle = static_cast<std::int64_t>(slot + 1U);
3936 return true;
3937 }
3938 }
3939 return false;
3940 }
3941
3942 template <std::size_t Capacity>
3943 static bool find_profile_handle(
3944 const std::array<BindingProfileSlot, Capacity> &profiles,
3945 const generated::StBindingNativeSequenceValue &sequence,
3946 std::int64_t &handle)
3947 {
3948 for(std::size_t slot = 0; slot < profiles.size(); ++slot) {
3949 if(profiles[slot].count == sequence.count &&
3950 profiles[slot].segments.data() == sequence.data) {
3951 handle = static_cast<std::int64_t>(slot + 1U);
3952 return true;
3953 }
3954 }
3955 return false;
3956 }
3957
3958 static bool rd16(const std::uint8_t *code, std::size_t size,
3959 std::size_t &pc, std::uint16_t &value)
3960 {
3961 if(pc + 2 > size) {
3962 return false;
3963 }
3964 value = static_cast<std::uint16_t>(
3965 static_cast<std::uint16_t>(code[pc]) |
3966 (static_cast<std::uint16_t>(code[pc + 1]) << 8));
3967 pc += 2;
3968 return true;
3969 }
3970
3971 static std::uint32_t read_le32(const unsigned char *bytes)
3972 {
3973 return static_cast<std::uint32_t>(bytes[0]) |
3974 (static_cast<std::uint32_t>(bytes[1]) << 8U) |
3975 (static_cast<std::uint32_t>(bytes[2]) << 16U) |
3976 (static_cast<std::uint32_t>(bytes[3]) << 24U);
3977 }
3978
3979 static bool next_utf8(const unsigned char *bytes, std::uint32_t length,
3980 std::uint32_t &at, std::uint32_t &scalar)
3981 {
3982 if(at >= length) {
3983 return false;
3984 }
3985 const std::uint8_t lead = bytes[at++];
3986 unsigned count = 0;
3987 if(lead < 0x80U) {
3988 scalar = lead;
3989 return true;
3990 }
3991 if(lead >= 0xC2U && lead <= 0xDFU) {
3992 scalar = lead & 0x1FU;
3993 count = 1;
3994 } else if(lead >= 0xE0U && lead <= 0xEFU) {
3995 scalar = lead & 0x0FU;
3996 count = 2;
3997 } else if(lead >= 0xF0U && lead <= 0xF4U) {
3998 scalar = lead & 0x07U;
3999 count = 3;
4000 } else {
4001 return false;
4002 }
4003 if(count > length - at) {
4004 return false;
4005 }
4006 for(unsigned i = 0; i < count; ++i) {
4007 const std::uint8_t part = bytes[at++];
4008 if((part & 0xC0U) != 0x80U) {
4009 return false;
4010 }
4011 if(i == 0U &&
4012 ((lead == 0xE0U && part < 0xA0U) ||
4013 (lead == 0xEDU && part > 0x9FU) ||
4014 (lead == 0xF0U && part < 0x90U) ||
4015 (lead == 0xF4U && part > 0x8FU))) {
4016 return false;
4017 }
4018 scalar = (scalar << 6U) | (part & 0x3FU);
4019 }
4020 return scalar <= 0x10FFFFU &&
4021 !(scalar >= 0xD800U && scalar <= 0xDFFFU);
4022 }
4023
4024 static bool valid_string_object(const unsigned char *object,
4025 const TypeDesc &desc)
4026 {
4027 const std::uint32_t length = read_le32(object);
4028 if(length > desc.string.capacity) {
4029 return false;
4030 }
4031 if(desc.kind == TypeKind::wstring) {
4032 for(std::uint32_t i = 0; i < length; ++i) {
4033 const std::uint32_t scalar =
4034 read_le32(object + 4U +
4035 static_cast<std::size_t>(i) * 4U);
4036 if(scalar > 0x10FFFFU ||
4037 (scalar >= 0xD800U && scalar <= 0xDFFFU)) {
4038 return false;
4039 }
4040 }
4041 return true;
4042 }
4043 if(desc.kind != TypeKind::string) {
4044 return false;
4045 }
4046 std::uint32_t at = 0;
4047 while(at < length) {
4048 std::uint32_t scalar = 0;
4049 if(!next_utf8(object + 4U, length, at, scalar)) {
4050 return false;
4051 }
4052 }
4053 return true;
4054 }
4055
4056 static int compare_strings(const unsigned char *left,
4057 const TypeDesc &left_desc,
4058 const unsigned char *right,
4059 const TypeDesc &right_desc)
4060 {
4061 if(!valid_string_object(left, left_desc) ||
4062 !valid_string_object(right, right_desc)) {
4063 return 2;
4064 }
4065 const std::uint32_t left_length = read_le32(left);
4066 const std::uint32_t right_length = read_le32(right);
4067 if(left_desc.kind == TypeKind::wstring) {
4068 const std::uint32_t common = left_length < right_length
4069 ? left_length
4070 : right_length;
4071 for(std::uint32_t i = 0; i < common; ++i) {
4072 const std::size_t byte_offset =
4073 static_cast<std::size_t>(i) * 4U;
4074 const std::uint32_t a = read_le32(left + 4U + byte_offset);
4075 const std::uint32_t b = read_le32(right + 4U + byte_offset);
4076 if(a != b) {
4077 return a < b ? -1 : 1;
4078 }
4079 }
4080 return left_length == right_length ? 0
4081 : left_length < right_length ? -1 : 1;
4082 }
4083 std::uint32_t left_at = 0;
4084 std::uint32_t right_at = 0;
4085 while(left_at < left_length && right_at < right_length) {
4086 std::uint32_t a = 0;
4087 std::uint32_t b = 0;
4088 if(!next_utf8(left + 4U, left_length, left_at, a) ||
4089 !next_utf8(right + 4U, right_length, right_at, b)) {
4090 return 2;
4091 }
4092 if(a != b) {
4093 return a < b ? -1 : 1;
4094 }
4095 }
4096 return left_at == left_length && right_at == right_length ? 0
4097 : left_at == left_length ? -1 : 1;
4098 }
4099
4100 static bool rd32(const std::uint8_t *code, std::size_t size,
4101 std::size_t &pc, std::uint32_t &value)
4102 {
4103 if(pc + 4 > size) {
4104 return false;
4105 }
4106 value = static_cast<std::uint32_t>(code[pc]) |
4107 (static_cast<std::uint32_t>(code[pc + 1]) << 8) |
4108 (static_cast<std::uint32_t>(code[pc + 2]) << 16) |
4109 (static_cast<std::uint32_t>(code[pc + 3]) << 24);
4110 pc += 4;
4111 return true;
4112 }
4113
4114 static bool rd64(const std::uint8_t *code, std::size_t size,
4115 std::size_t &pc, std::uint64_t &value)
4116 {
4117 std::uint32_t low = 0;
4118 std::uint32_t high = 0;
4119 if(!rd32(code, size, pc, low) || !rd32(code, size, pc, high)) {
4120 return false;
4121 }
4122 value = static_cast<std::uint64_t>(low) |
4123 (static_cast<std::uint64_t>(high) << 32U);
4124 return true;
4125 }
4126
4127 bool load_raw64_at(const unsigned char *storage, std::uint32_t offset,
4128 std::uint64_t &value) const
4129 {
4130 if(program_ == nullptr || offset > program_->vars_bytes ||
4131 8U > program_->vars_bytes - offset) {
4132 return false;
4133 }
4134 std::memcpy(&value, storage + offset, sizeof(value));
4135 return true;
4136 }
4137
4138 bool load_raw64(std::uint32_t offset, std::uint64_t &value) const
4139 {
4140 return load_raw64_at(execution_vars_, offset, value);
4141 }
4142
4143 bool store_raw64(std::uint32_t offset, std::uint64_t value)
4144 {
4145 if(program_ == nullptr || offset > program_->vars_bytes ||
4146 8U > program_->vars_bytes - offset) {
4147 return false;
4148 }
4149 std::memcpy(execution_vars_ + offset, &value, sizeof(value));
4150 return true;
4151 }
4152
4153 bool load_value(std::uint32_t offset, TypeId type_id,
4154 std::uint64_t &value) const
4155 {
4156 return load_value_at(execution_vars_, offset, type_id, value);
4157 }
4158
4159 bool load_value_at(const unsigned char *storage, std::uint32_t offset,
4160 TypeId type_id, std::uint64_t &value) const
4161 {
4162 if(program_ == nullptr || storage == nullptr) {
4163 return false;
4164 }
4165 const TypeDesc *desc = program_->types.get(type_id);
4166 if(desc == nullptr) {
4167 return type_id == invalid_type_id &&
4168 load_raw64_at(storage, offset, value);
4169 }
4170 if(desc->kind == TypeKind::array || desc->kind == TypeKind::struct_ ||
4171 desc->size == 0 || desc->size > 8 ||
4172 offset > program_->vars_bytes ||
4173 desc->size > program_->vars_bytes - offset) {
4174 return false;
4175 }
4176 std::uint64_t raw = 0;
4177 for(std::uint64_t i = 0; i < desc->size; ++i) {
4178 raw |= static_cast<std::uint64_t>(storage[offset + i]) <<
4179 (i * 8U);
4180 }
4181 TypeId base_id = type_id;
4182 if(desc->kind == TypeKind::enum_) {
4183 base_id = desc->enum_base;
4184 } else if(desc->kind == TypeKind::subrange) {
4185 base_id = desc->subrange.base;
4186 }
4187 const Type type = type_from_id(base_id);
4188 if(type == Type::real) {
4189 const std::uint32_t raw32 = static_cast<std::uint32_t>(raw);
4190 float number = 0.0F;
4191 std::memcpy(&number, &raw32, sizeof(number));
4192 value = detail::double_bits(static_cast<double>(number));
4193 return true;
4194 }
4195 if((is_signed_int(type) || type == Type::date) && desc->size < 8) {
4196 const unsigned bits = static_cast<unsigned>(desc->size * 8U);
4197 const std::uint64_t sign = std::uint64_t{1} << (bits - 1U);
4198 raw = (raw ^ sign) - sign;
4199 }
4200 value = raw;
4201 return true;
4202 }
4203
4204 bool store_value(std::uint32_t offset, TypeId type_id,
4205 std::uint64_t value)
4206 {
4207 if(program_ == nullptr) {
4208 return false;
4209 }
4210 if(process_image_ != nullptr) {
4211 (void)process_image_->forced_store(*program_, offset, type_id,
4212 value);
4213 }
4214 const TypeDesc *desc = program_->types.get(type_id);
4215 if(desc == nullptr) {
4216 return type_id == invalid_type_id && store_raw64(offset, value);
4217 }
4218 if(desc->kind == TypeKind::array || desc->kind == TypeKind::struct_ ||
4219 desc->size == 0 || desc->size > 8 ||
4220 offset > program_->vars_bytes ||
4221 desc->size > program_->vars_bytes - offset) {
4222 return false;
4223 }
4224 TypeId base_id = type_id;
4225 if(desc->kind == TypeKind::enum_) {
4226 base_id = desc->enum_base;
4227 } else if(desc->kind == TypeKind::subrange) {
4228 base_id = desc->subrange.base;
4229 }
4230 if(type_from_id(base_id) == Type::real) {
4231 const float number =
4232 static_cast<float>(detail::bits_double(value));
4233 std::uint32_t raw = 0;
4234 std::memcpy(&raw, &number, sizeof(raw));
4235 value = raw;
4236 }
4237 for(std::uint64_t i = 0; i < desc->size; ++i) {
4238 execution_vars_[offset + i] =
4239 static_cast<unsigned char>(value >> (i * 8U));
4240 }
4241 if(process_image_ != nullptr)
4242 process_image_->mark_store(*program_, offset, type_id);
4243 return true;
4244 }
4245
4246 static std::int64_t as_i64(std::uint64_t raw)
4247 {
4248 return static_cast<std::int64_t>(raw);
4249 }
4250
4251 static std::uint64_t as_u64(std::int64_t value)
4252 {
4253 return static_cast<std::uint64_t>(value);
4254 }
4255
4256 DebugRuntimeStorage *debug_runtime_storage() noexcept
4257 {
4258 if(program_ == nullptr || vars_ == nullptr ||
4259 !program_->needs_debug_runtime_storage())
4260 return nullptr;
4261 return reinterpret_cast<DebugRuntimeStorage *>(
4262 vars_ + program_->debug_runtime_storage_offset());
4263 }
4264
4265 const DebugRuntimeStorage *debug_runtime_storage() const noexcept
4266 {
4267 if(program_ == nullptr || vars_ == nullptr ||
4268 !program_->needs_debug_runtime_storage())
4269 return nullptr;
4270 return reinterpret_cast<const DebugRuntimeStorage *>(
4271 vars_ + program_->debug_runtime_storage_offset());
4272 }
4273
4274 ScanError latch(ScanError error)
4275 {
4276 if(sfc_runner_->active_region != nullptr &&
4277 sfc_runner_->network_index < program_->sfc_networks.size()) {
4278 sfc_runner_->fault_network_index =
4279 static_cast<std::uint32_t>(sfc_runner_->network_index);
4280 sfc_runner_->fault_element_index =
4281 static_cast<std::uint32_t>(sfc_runner_->item_index);
4282 sfc_runner_->fault_element_kind =
4283 sfc_runner_->phase == SfcRunnerPhase::transitions
4284 ? TaskFaultElementKind::transition
4285 : TaskFaultElementKind::action;
4286 }
4287 if(sfc_commit_started()) rollback_sfc_commit();
4288 execution_vars_ = vars_;
4289 visible_vars_ = vars_;
4290 sfc_runner_->trace_size = sfc_runner_->trace_scan_begin_size;
4291 sfc_runner_->trace_dropped = sfc_runner_->trace_scan_begin_dropped;
4292 sfc_runner_->active_region = nullptr;
4293 fault_ = error;
4294 execution_state_ = InstanceState::faulted;
4295 return error;
4296 }
4297
4298 const Program *program_ = nullptr;
4299 ProcessImage *process_image_ = nullptr;
4300 unsigned char *vars_ = nullptr;
4301 const unsigned char *visible_vars_ = nullptr;
4302 unsigned char *execution_vars_ = nullptr;
4303 unsigned char *sfc_runtime_ = nullptr;
4304 SfcRunnerStorage *sfc_runner_ = nullptr;
4305 unsigned char *fb_area_ = nullptr;
4306 std::uint64_t *stack_ = nullptr;
4307 ScanError fault_ = ScanError::ok;
4308 InstanceState execution_state_ = InstanceState::idle;
4309 std::size_t pc_ = 0;
4310 std::uint32_t instruction_pc_ = 0;
4311 std::int32_t sp_ = 0;
4312 std::int64_t remaining_budget_ = 0;
4313 bool scan_started_ = false;
4314 bool defer_process_image_publish_ = false;
4315 std::int64_t task_period_ns_ = 0;
4316 std::int64_t utc_dt_ns_ = 0;
4317 RuntimeDebugHooks *debug_hooks_ = nullptr;
4318 AxisTargetStorage *axis_targets_ = nullptr;
4319 GroupTargetStorage *group_targets_ = nullptr;
4320 PathTableStorage *path_tables_ = nullptr;
4321 PathDescriptionStorage *path_descriptions_ = nullptr;
4322 CamSwitchTableStorage *cam_switch_tables_ = nullptr;
4323 CamSwitchOutputStorage *cam_switch_outputs_ = nullptr;
4324 CamTrackOptionStorage *cam_track_options_ = nullptr;
4325 CamTableStorage *cam_tables_ = nullptr;
4326 PositionProfileStorage *position_profiles_ = nullptr;
4327 VelocityProfileStorage *velocity_profiles_ = nullptr;
4328 AccelerationProfileStorage *acceleration_profiles_ = nullptr;
4329 KinTransformStorage *kin_transforms_ = nullptr;
4330};
4331
4332} // namespace plcopen::core::st
static constexpr std::size_t DigitalOutputCount
constexpr BindingTargetKind kind() const
constexpr void * pointer() const
static constexpr BindingTarget group(axis::AxisGroup *value)
static constexpr BindingTarget axis(axis::AxisModel *value)
Instance & operator=(const Instance &)=delete
BindingError bind_path_description(const char *name, const fb::PathWaypoint *waypoints, std::size_t count)
定义 vm.h:355
rt::ErrorCode load(const Program &program, unsigned char *buffer, std::size_t buffer_bytes, std::int64_t task_period_ns)
定义 vm.h:141
BindingError bind_position_profile(const char *name, const BindingPositionProfileEntry *entries, std::size_t count)
定义 vm.h:497
BindingError bind_cam_switch_outputs(const char *name, bool *data, std::size_t count)
定义 vm.h:452
std::uint32_t fault_sfc_element_index() const noexcept
定义 vm.h:741
bool value_bool(std::size_t index) const
定义 vm.h:2754
const VarInfo * variable(std::size_t index) const
定义 vm.h:2695
BindingError bind_group(const char *name, axis::AxisGroup *group)
定义 vm.h:279
const SourceMapEntry * last_debug_entry() const noexcept
定义 vm.h:641
bool debug_sfc_committed_step_active(std::size_t network, std::size_t step) const noexcept
定义 vm.h:693
std::int64_t remaining_budget() const noexcept
定义 vm.h:616
BindingError bind_cam_switch_table(const char *name, const fb::CamSwitchAction *data, std::size_t count)
定义 vm.h:413
Instance(const Instance &)=delete
double value_f64(std::size_t index) const
定义 vm.h:2742
BindingError bind_kin_transform(const char *name, axis::KinTransformRef transform)
定义 vm.h:385
void unload() noexcept
定义 vm.h:98
std::uint64_t sfc_trace_dropped() const noexcept
定义 vm.h:720
InstanceState execution_state() const noexcept
定义 vm.h:602
BindingError bind_acceleration_profile(const char *name, const BindingAccelerationProfileEntry *entries, std::size_t count)
定义 vm.h:564
std::size_t sfc_trace_size() const noexcept
定义 vm.h:719
Instance & operator=(Instance &&)=delete
ScanError scan(std::int64_t budget)
定义 vm.h:813
rt::ErrorCode inject_utc_dt(std::int64_t value) noexcept
定义 vm.h:91
bool complete() const noexcept
定义 vm.h:607
rt::ErrorCode sfc_step_active(const char *network_name, const char *step_name, bool &active) const noexcept
定义 vm.h:668
std::uint32_t fault_sfc_network_index() const noexcept
定义 vm.h:737
BindingError bind_velocity_profile(const char *name, const BindingVelocityProfileEntry *entries, std::size_t count)
定义 vm.h:532
const InstructionId & last_debug_instruction_id() const noexcept
定义 vm.h:648
std::int64_t utc_dt_ns() const noexcept
定义 vm.h:96
BindingError bind_cam_table(const char *name, const exec::CamPoint *data, std::size_t count, bool periodic)
定义 vm.h:483
void abort() noexcept
定义 vm.h:788
int find(const char *name) const
定义 vm.h:2704
rt::ErrorCode load(const Program &program, unsigned char *buffer, std::size_t buffer_bytes, std::int64_t task_period_ns, ProcessImage *process_image)
定义 vm.h:210
ScanError fault() const
定义 vm.h:597
BindingError bind_reference(const char *name, BindingTarget target)
定义 vm.h:284
Instance(Instance &&)=delete
std::size_t variable_count() const
定义 vm.h:2690
rt::ErrorCode restart_sfc(const char *network_name) noexcept
定义 vm.h:725
const Program * program() const noexcept
定义 vm.h:639
bool read_variable(std::uint32_t offset, std::uint32_t size, unsigned char *destination) const noexcept
定义 vm.h:657
ScanError begin(std::int64_t budget)
定义 vm.h:750
BindingError bind_axis(const char *name, axis::AxisModel *axis)
定义 vm.h:274
ScanError resume(std::int64_t slice, std::int64_t &executed)
定义 vm.h:823
void defer_process_image_publish(bool defer) noexcept
定义 vm.h:612
const char * program_name() const noexcept
定义 vm.h:624
TaskFaultElementKind fault_sfc_element_kind() const noexcept
定义 vm.h:745
bool running() const noexcept
定义 vm.h:603
std::int64_t value_i64(std::size_t index) const
定义 vm.h:2730
BindingError bind_cam_track_options(const char *name, const fb::CamTrackOption *data, std::size_t count)
定义 vm.h:467
BindingError bind_path_table(const char *name, fb::PathTable *table)
定义 vm.h:344
std::uint32_t instruction_offset() const noexcept
定义 vm.h:620
void set_debug_hooks(RuntimeDebugHooks *hooks, std::size_t mapping) noexcept
定义 vm.h:629
rt::ErrorCode load(const Program &program, const char *program_name, unsigned char *buffer, std::size_t buffer_bytes, std::int64_t task_period_ns)
定义 vm.h:223
rt::ErrorCode configure_sfc_trace(SfcTraceRecord *records, std::size_t capacity) noexcept
定义 vm.h:704
bool supports(const Program &program) const noexcept
rt::ErrorCode validate_path_waypoint(const PathWaypoint &waypoint, std::size_t axis_count)
std::uint64_t double_bits(double value)
std::int64_t wrap_add64(std::int64_t a, std::int64_t b)
std::uint64_t canon(Type type, std::uint64_t raw)
std::int64_t wrap_sub64(std::int64_t a, std::int64_t b)
std::int64_t wrap16(std::int64_t value)
std::uint64_t wrap_double_to_u64(double value)
std::int64_t wrap_mul64(std::int64_t a, std::int64_t b)
double bits_double(std::uint64_t bits)
std::int64_t wrap32(std::int64_t value)
constexpr bool st_binding_time_ns_to_cycles(std::int64_t time_ns, std::int64_t task_period_ns, std::int64_t &cycles) noexcept
constexpr bool st_binding_can_store_tagged_reference(StBindingFbType type, std::uint16_t pin) noexcept
constexpr bool st_binding_can_load_sequence(StBindingFbType type, std::uint16_t pin) noexcept
constexpr bool st_binding_can_store_sequence(StBindingFbType type, std::uint16_t pin) noexcept
constexpr bool st_binding_can_load_tagged_reference(StBindingFbType type, std::uint16_t pin) noexcept
std::array< exec::CamTableView, kMaxTableBindings > CamTableStorage
std::uint32_t TypeId
constexpr int width_bits(Type type)
std::array< axis::AxisGroup *, kMaxGroupBindings > GroupTargetStorage
bool fb_load_object(FbType type, const unsigned char *storage, std::uint8_t pin, unsigned char *bytes, TypeId type_id, std::uint32_t size) noexcept
定义 bind.h:61
bool fb_store_tagged_reference(FbType type, unsigned char *storage, std::uint16_t pin, TypeId type_id, generated::StBindingNativeTaggedReferenceValue value) noexcept
定义 bind.h:83
void fb_cycle(FbType type, unsigned char *storage, std::int64_t task_period_ns=0)
定义 bind.h:100
bool fb_store_scalar(FbType type, unsigned char *storage, std::uint16_t pin, std::uint64_t bits) noexcept
定义 bind.h:41
std::array< fb::PathDescription, kMaxTableBindings > PathDescriptionStorage
constexpr bool is_real_family(Type type)
std::array< axis::AxisModel *, kMaxAxisBindings > AxisTargetStorage
bool fb_store_object(FbType type, unsigned char *storage, std::uint8_t pin, const unsigned char *bytes, TypeId type_id, std::uint32_t size) noexcept
定义 bind.h:53
constexpr const char * to_string(ConvKind kind)
定义 conv.h:90
std::array< fb::CamSwitchOutputsView, kMaxTableBindings > CamSwitchOutputStorage
constexpr PinTable pin_table(FbType type) noexcept
定义 pins.h:56
PositionProfileStorage AccelerationProfileStorage
void fb_init(FbType type, unsigned char *storage, std::int64_t task_period_ns)
定义 bind.h:15
bool fb_store_sequence(FbType type, unsigned char *storage, std::uint16_t pin, generated::StBindingNativeSequenceValue value) noexcept
定义 bind.h:69
constexpr std::uint32_t kBytecodeFormatVersion
PositionProfileStorage VelocityProfileStorage
bool fb_load_tagged_reference(FbType type, const unsigned char *storage, std::uint16_t pin, TypeId type_id, generated::StBindingNativeTaggedReferenceValue &value) noexcept
定义 bind.h:91
void fb_destroy(FbType type, unsigned char *storage) noexcept
定义 bind.h:36
std::array< BindingProfileSlot, kMaxTableBindings > PositionProfileStorage
constexpr bool is_unsigned_int(Type type)
constexpr std::uint32_t standard_string_cost(StandardFunction function, const std::uint32_t *capacities, std::uint8_t count, std::uint32_t destination_capacity)
constexpr TypeId type_id(Type type)
定义 types.h:52
constexpr bool is_signed_int(Type type)
bool fb_load_scalar(FbType type, const unsigned char *storage, std::uint16_t pin, std::uint64_t &bits) noexcept
定义 bind.h:47
std::array< fb::PathTable *, kMaxTableBindings > PathTableStorage
std::array< axis::KinTransformRef, kMaxTableBindings > KinTransformStorage
bool fb_load_sequence(FbType type, const unsigned char *storage, std::uint16_t pin, generated::StBindingNativeSequenceValue &value) noexcept
定义 bind.h:76
constexpr TypeId invalid_type_id
std::array< fb::CamTrackOptionsView, kMaxTableBindings > CamTrackOptionStorage
constexpr Type type_from_id(TypeId id)
定义 types.h:84
std::array< fb::CamSwitchTableView, kMaxTableBindings > CamSwitchTableStorage
constexpr bool is_bitstring(Type type)
static constexpr std::size_t MaxAxes
定义 group.h:29
const kin::Kinematics * kinematics
const kin::PoseKinematics * pose
PathWaypoint waypoints[MaxWaypoints]
static constexpr std::size_t MaxWaypoints
std::array< axis::ProfileSegment, kMaxProfileSegments > segments
constexpr std::int64_t as_signed() const
constexpr std::uint64_t as_unsigned() const
std::vector< SfcStepInfo > steps
std::vector< SourceMapEntry > entries
std::vector< EnumItem > enum_items