Difficulty: Medium · Puzzle 4 of 6 · Topic: Handle and Copy Puzzles
This `do_copy` tries to deep-copy nested policy object, but simulation crashes with null-handle access. Identify root cause and fix.
class qos extends uvm_object;
`uvm_object_utils(qos)
int prio;
function new(string name="qos"); super.new(name); endfunction
endclass
class pkt extends uvm_sequence_item;
`uvm_object_utils(pkt)
qos policy;
function new(string name="pkt");
super.new(name);
endfunction
function void do_copy(uvm_object rhs);
pkt r;
if (!$cast(r, rhs)) return;
policy.copy(r.policy);
endfunction
endclassBefore calling `policy.copy(...)`, what must be true about destination handle allocation?
1) `policy` is never constructed in `new`, so destination handle remains null.
2) `policy.copy(r.policy)` dereferences null and triggers runtime fatal/null-handle error.
3) Allocate destination before copy (`if (policy == null) policy = qos::type_id::create(...)`).
4) Also guard source null case and set destination null accordingly.
5) The override also never calls `super.do_copy(rhs)`, so base-class state is skipped as well.Answer: Crash occurs because `policy` is null in destination (never built in `new`); `policy.copy(r.policy)` dereferences an unallocated nested handle. Fix: call `super.do_copy(rhs)`, then if `r.policy == null` set `policy = null`, else allocate `policy` if needed and `policy.copy(r.policy)`.
Checked by running the code in Verilator 5; the printed output supports the answer above. A hand-written model (not the UVM library): the destination policy handle is null until something allocates it, so the guarded copy allocates first.
`policy.copy(...)` copies into an existing object; it never allocates the destination. The null is on the left of the dot, not the right.
How would you implement symmetric null-handling so copy preserves null vs non-null state exactly? Model answer: `if (r.policy == null) policy = null; else begin if (policy == null) policy = qos::type_id::create("policy"); policy.copy(r.policy); end`. Both null and non-null cases then leave source and destination in the same state, and the destination object is reused when it already exists.
It crashes with a null handle error, because the policy handle is never built in the constructor, so copying into it dereferences null. The override also never calls super do_copy, so base-class state is skipped too. The trap is only noticing the null and missing the missing super call. I would call super do_copy first, set the policy to null if the source is null, otherwise allocate it if needed and copy, and then test both the null and non-null cases.