identifying locations where big/little endian is in place, adding args
[soc.git] / src / soc / decoder / isa / caller.py
1 """core of the python-based POWER9 simulator
2
3 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
4 not speed, it is for both learning and educational purposes, as well as
5 a method of verifying the HDL.
6 """
7
8 from functools import wraps
9 from soc.decoder.orderedset import OrderedSet
10 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
11 selectconcat)
12 from soc.decoder.power_enums import (spr_dict, spr_byname, XER_bits,
13 insns, InternalOp)
14 from soc.decoder.helpers import exts, trunc_div, trunc_rem
15 from soc.consts import PI, MSR
16
17 from collections import namedtuple
18 import math
19 import sys
20
21 instruction_info = namedtuple('instruction_info',
22 'func read_regs uninit_regs write_regs ' + \
23 'special_regs op_fields form asmregs')
24
25 special_sprs = {
26 'LR': 8,
27 'CTR': 9,
28 'TAR': 815,
29 'XER': 1,
30 'VRSAVE': 256}
31
32
33 def swap_order(x, nbytes):
34 x = x.to_bytes(nbytes, byteorder='little')
35 x = int.from_bytes(x, byteorder='big', signed=False)
36 return x
37
38
39 def create_args(reglist, extra=None):
40 args = OrderedSet()
41 for reg in reglist:
42 args.add(reg)
43 args = list(args)
44 if extra:
45 args = [extra] + args
46 return args
47
48
49 class Mem:
50
51 def __init__(self, row_bytes=8, initial_mem=None):
52 self.mem = {}
53 self.bytes_per_word = row_bytes
54 self.word_log2 = math.ceil(math.log2(row_bytes))
55 print ("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
56 if not initial_mem:
57 return
58
59 # different types of memory data structures recognised (for convenience)
60 if isinstance(initial_mem, list):
61 initial_mem = (0, initial_mem)
62 if isinstance(initial_mem, tuple):
63 startaddr, mem = initial_mem
64 initial_mem = {}
65 for i, val in enumerate(mem):
66 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
67
68 for addr, (val, width) in initial_mem.items():
69 #val = swap_order(val, width)
70 self.st(addr, val, width, swap=False)
71
72 def _get_shifter_mask(self, wid, remainder):
73 shifter = ((self.bytes_per_word - wid) - remainder) * \
74 8 # bits per byte
75 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
76 # BE/LE mode?
77 shifter = remainder * 8
78 mask = (1 << (wid * 8)) - 1
79 print ("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
80 return shifter, mask
81
82 # TODO: Implement ld/st of lesser width
83 def ld(self, address, width=8, swap=True, check_in_mem=False):
84 print("ld from addr 0x{:x} width {:d}".format(address, width))
85 remainder = address & (self.bytes_per_word - 1)
86 address = address >> self.word_log2
87 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
88 if address in self.mem:
89 val = self.mem[address]
90 elif check_in_mem:
91 return None
92 else:
93 val = 0
94 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
95
96 if width != self.bytes_per_word:
97 shifter, mask = self._get_shifter_mask(width, remainder)
98 print ("masking", hex(val), hex(mask<<shifter), shifter)
99 val = val & (mask << shifter)
100 val >>= shifter
101 if swap:
102 val = swap_order(val, width)
103 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
104 return val
105
106 def st(self, addr, v, width=8, swap=True):
107 staddr = addr
108 remainder = addr & (self.bytes_per_word - 1)
109 addr = addr >> self.word_log2
110 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v,
111 staddr, addr, remainder, swap))
112 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
113 if swap:
114 v = swap_order(v, width)
115 if width != self.bytes_per_word:
116 if addr in self.mem:
117 val = self.mem[addr]
118 else:
119 val = 0
120 shifter, mask = self._get_shifter_mask(width, remainder)
121 val &= ~(mask << shifter)
122 val |= v << shifter
123 self.mem[addr] = val
124 else:
125 self.mem[addr] = v
126 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
127
128 def __call__(self, addr, sz):
129 val = self.ld(addr.value, sz)
130 print ("memread", addr, sz, val)
131 return SelectableInt(val, sz*8)
132
133 def memassign(self, addr, sz, val):
134 print ("memassign", addr, sz, val)
135 self.st(addr.value, val.value, sz)
136
137
138 class GPR(dict):
139 def __init__(self, decoder, regfile):
140 dict.__init__(self)
141 self.sd = decoder
142 for i in range(32):
143 self[i] = SelectableInt(regfile[i], 64)
144
145 def __call__(self, ridx):
146 return self[ridx]
147
148 def set_form(self, form):
149 self.form = form
150
151 def getz(self, rnum):
152 #rnum = rnum.value # only SelectableInt allowed
153 print("GPR getzero", rnum)
154 if rnum == 0:
155 return SelectableInt(0, 64)
156 return self[rnum]
157
158 def _get_regnum(self, attr):
159 getform = self.sd.sigforms[self.form]
160 rnum = getattr(getform, attr)
161 return rnum
162
163 def ___getitem__(self, attr):
164 print("GPR getitem", attr)
165 rnum = self._get_regnum(attr)
166 return self.regfile[rnum]
167
168 def dump(self):
169 for i in range(0, len(self), 8):
170 s = []
171 for j in range(8):
172 s.append("%08x" % self[i+j].value)
173 s = ' '.join(s)
174 print("reg", "%2d" % i, s)
175
176 class PC:
177 def __init__(self, pc_init=0):
178 self.CIA = SelectableInt(pc_init, 64)
179 self.NIA = self.CIA + SelectableInt(4, 64)
180
181 def update(self, namespace):
182 self.CIA = namespace['NIA'].narrow(64)
183 self.NIA = self.CIA + SelectableInt(4, 64)
184 namespace['CIA'] = self.CIA
185 namespace['NIA'] = self.NIA
186
187
188 class SPR(dict):
189 def __init__(self, dec2, initial_sprs={}):
190 self.sd = dec2
191 dict.__init__(self)
192 for key, v in initial_sprs.items():
193 if isinstance(key, SelectableInt):
194 key = key.value
195 key = special_sprs.get(key, key)
196 if isinstance(key, int):
197 info = spr_dict[key]
198 else:
199 info = spr_byname[key]
200 if not isinstance(v, SelectableInt):
201 v = SelectableInt(v, info.length)
202 self[key] = v
203
204 def __getitem__(self, key):
205 print ("get spr", key)
206 print ("dict", self.items())
207 # if key in special_sprs get the special spr, otherwise return key
208 if isinstance(key, SelectableInt):
209 key = key.value
210 if isinstance(key, int):
211 key = spr_dict[key].SPR
212 key = special_sprs.get(key, key)
213 if key in self:
214 res = dict.__getitem__(self, key)
215 else:
216 if isinstance(key, int):
217 info = spr_dict[key]
218 else:
219 info = spr_byname[key]
220 dict.__setitem__(self, key, SelectableInt(0, info.length))
221 res = dict.__getitem__(self, key)
222 print ("spr returning", key, res)
223 return res
224
225 def __setitem__(self, key, value):
226 if isinstance(key, SelectableInt):
227 key = key.value
228 if isinstance(key, int):
229 key = spr_dict[key].SPR
230 print ("spr key", key)
231 key = special_sprs.get(key, key)
232 print ("setting spr", key, value)
233 dict.__setitem__(self, key, value)
234
235 def __call__(self, ridx):
236 return self[ridx]
237
238
239 class ISACaller:
240 # decoder2 - an instance of power_decoder2
241 # regfile - a list of initial values for the registers
242 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
243 # respect_pc - tracks the program counter. requires initial_insns
244 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
245 initial_mem=None, initial_msr=0,
246 initial_insns=None, respect_pc=False,
247 disassembly=None,
248 initial_pc=0,
249 bigendian=True):
250
251 self.bigendian = bigendian
252 self.halted = False
253 self.respect_pc = respect_pc
254 if initial_sprs is None:
255 initial_sprs = {}
256 if initial_mem is None:
257 initial_mem = {}
258 if initial_insns is None:
259 initial_insns = {}
260 assert self.respect_pc == False, "instructions required to honor pc"
261
262 print ("ISACaller insns", respect_pc, initial_insns, disassembly)
263
264 # "fake program counter" mode (for unit testing)
265 self.fake_pc = 0
266 disasm_start = 0
267 if not respect_pc:
268 if isinstance(initial_mem, tuple):
269 self.fake_pc = initial_mem[0]
270 disasm_start = self.fake_pc
271 else:
272 disasm_start = initial_pc
273
274 # disassembly: we need this for now (not given from the decoder)
275 self.disassembly = {}
276 if disassembly:
277 for i, code in enumerate(disassembly):
278 self.disassembly[i*4 + disasm_start] = code
279
280 # set up registers, instruction memory, data memory, PC, SPRs, MSR
281 self.gpr = GPR(decoder2, regfile)
282 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
283 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
284 self.pc = PC()
285 self.spr = SPR(decoder2, initial_sprs)
286 self.msr = SelectableInt(initial_msr, 64) # underlying reg
287
288 # TODO, needed here:
289 # FPR (same as GPR except for FP nums)
290 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
291 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
292 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
293 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
294 # -- Done
295 # 2.3.2 LR (actually SPR #8) -- Done
296 # 2.3.3 CTR (actually SPR #9) -- Done
297 # 2.3.4 TAR (actually SPR #815)
298 # 3.2.2 p45 XER (actually SPR #1) -- Done
299 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
300
301 # create CR then allow portions of it to be "selectable" (below)
302 self._cr = SelectableInt(initial_cr, 64) # underlying reg
303 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
304
305 # "undefined", just set to variable-bit-width int (use exts "max")
306 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
307
308 self.namespace = {}
309 self.namespace.update(self.spr)
310 self.namespace.update({'GPR': self.gpr,
311 'MEM': self.mem,
312 'SPR': self.spr,
313 'memassign': self.memassign,
314 'NIA': self.pc.NIA,
315 'CIA': self.pc.CIA,
316 'CR': self.cr,
317 'MSR': self.msr,
318 'undefined': self.undefined,
319 'mode_is_64bit': True,
320 'SO': XER_bits['SO']
321 })
322
323 # update pc to requested start point
324 self.set_pc(initial_pc)
325
326 # field-selectable versions of Condition Register TODO check bitranges?
327 self.crl = []
328 for i in range(8):
329 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
330 _cr = FieldSelectableInt(self.cr, bits)
331 self.crl.append(_cr)
332 self.namespace["CR%d" % i] = _cr
333
334 self.decoder = decoder2.dec
335 self.dec2 = decoder2
336
337 def TRAP(self, trap_addr=0x700, trap_bit=PI.TRAP):
338 print ("TRAP:", hex(trap_addr))
339 # store CIA(+4?) in SRR0, set NIA to 0x700
340 # store MSR in SRR1, set MSR to um errr something, have to check spec
341 self.spr['SRR0'] = self.pc.CIA
342 self.spr['SRR1'] = self.namespace['MSR']
343 self.trap_nia = SelectableInt(trap_addr, 64)
344 self.namespace['MSR'][63-trap_bit] = 1
345
346 def memassign(self, ea, sz, val):
347 self.mem.memassign(ea, sz, val)
348
349 def prep_namespace(self, formname, op_fields):
350 # TODO: get field names from form in decoder*1* (not decoder2)
351 # decoder2 is hand-created, and decoder1.sigform is auto-generated
352 # from spec
353 # then "yield" fields only from op_fields rather than hard-coded
354 # list, here.
355 fields = self.decoder.sigforms[formname]
356 for name in op_fields:
357 if name == 'spr':
358 sig = getattr(fields, name.upper())
359 else:
360 sig = getattr(fields, name)
361 val = yield sig
362 if name in ['BF', 'BFA']:
363 self.namespace[name] = val
364 else:
365 self.namespace[name] = SelectableInt(val, sig.width)
366
367 self.namespace['XER'] = self.spr['XER']
368 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
369 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
370
371 def handle_carry_(self, inputs, outputs, already_done):
372 inv_a = yield self.dec2.e.do.invert_a
373 if inv_a:
374 inputs[0] = ~inputs[0]
375
376 imm_ok = yield self.dec2.e.do.imm_data.ok
377 if imm_ok:
378 imm = yield self.dec2.e.do.imm_data.data
379 inputs.append(SelectableInt(imm, 64))
380 assert len(outputs) >= 1
381 print ("outputs", repr(outputs))
382 if isinstance(outputs, list) or isinstance(outputs, tuple):
383 output = outputs[0]
384 else:
385 output = outputs
386 gts = []
387 for x in inputs:
388 print ("gt input", x, output)
389 gt = (x > output)
390 gts.append(gt)
391 print(gts)
392 cy = 1 if any(gts) else 0
393 if not (1 & already_done):
394 self.spr['XER'][XER_bits['CA']] = cy
395
396 print ("inputs", inputs)
397 # 32 bit carry
398 gts = []
399 for x in inputs:
400 print ("input", x, output)
401 gt = (x[32:64] > output[32:64]) == SelectableInt(1, 1)
402 gts.append(gt)
403 cy32 = 1 if any(gts) else 0
404 if not (2 & already_done):
405 self.spr['XER'][XER_bits['CA32']] = cy32
406
407 def handle_overflow(self, inputs, outputs, div_overflow):
408 inv_a = yield self.dec2.e.do.invert_a
409 if inv_a:
410 inputs[0] = ~inputs[0]
411
412 imm_ok = yield self.dec2.e.do.imm_data.ok
413 if imm_ok:
414 imm = yield self.dec2.e.do.imm_data.data
415 inputs.append(SelectableInt(imm, 64))
416 assert len(outputs) >= 1
417 print ("handle_overflow", inputs, outputs, div_overflow)
418 if len(inputs) < 2 and div_overflow != 1:
419 return
420
421 # div overflow is different: it's returned by the pseudo-code
422 # because it's more complex than can be done by analysing the output
423 if div_overflow == 1:
424 ov, ov32 = 1, 1
425 # arithmetic overflow can be done by analysing the input and output
426 elif len(inputs) >= 2:
427 output = outputs[0]
428
429 # OV (64-bit)
430 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
431 output_sgn = exts(output.value, output.bits) < 0
432 ov = 1 if input_sgn[0] == input_sgn[1] and \
433 output_sgn != input_sgn[0] else 0
434
435 # OV (32-bit)
436 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
437 output32_sgn = exts(output.value, 32) < 0
438 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
439 output32_sgn != input32_sgn[0] else 0
440
441 self.spr['XER'][XER_bits['OV']] = ov
442 self.spr['XER'][XER_bits['OV32']] = ov32
443 so = self.spr['XER'][XER_bits['SO']]
444 so = so | ov
445 self.spr['XER'][XER_bits['SO']] = so
446
447 def handle_comparison(self, outputs):
448 out = outputs[0]
449 out = exts(out.value, out.bits)
450 zero = SelectableInt(out == 0, 1)
451 positive = SelectableInt(out > 0, 1)
452 negative = SelectableInt(out < 0, 1)
453 SO = self.spr['XER'][XER_bits['SO']]
454 cr_field = selectconcat(negative, positive, zero, SO)
455 self.crl[0].eq(cr_field)
456
457 def set_pc(self, pc_val):
458 self.namespace['NIA'] = SelectableInt(pc_val, 64)
459 self.pc.update(self.namespace)
460
461 def setup_one(self):
462 """set up one instruction
463 """
464 if self.respect_pc:
465 pc = self.pc.CIA.value
466 else:
467 pc = self.fake_pc
468 self._pc = pc
469 ins = self.imem.ld(pc, 4, False, True)
470 if ins is None:
471 raise KeyError("no instruction at 0x%x" % pc)
472 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
473 print ("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
474
475 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
476 yield self.dec2.dec.bigendian.eq(self.bigendian)
477
478 def execute_one(self):
479 """execute one instruction
480 """
481 # get the disassembly code for this instruction
482 code = self.disassembly[self._pc]
483 print("sim-execute", hex(self._pc), code)
484 opname = code.split(' ')[0]
485 yield from self.call(opname)
486
487 if not self.respect_pc:
488 self.fake_pc += 4
489 print ("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
490
491 def get_assembly_name(self):
492 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
493 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
494 asmcode = yield self.dec2.dec.op.asmcode
495 print ("get assembly name asmcode", asmcode)
496 asmop = insns.get(asmcode, None)
497
498 # sigh reconstruct the assembly instruction name
499 ov_en = yield self.dec2.e.do.oe.oe
500 ov_ok = yield self.dec2.e.do.oe.ok
501 if ov_en & ov_ok:
502 asmop += "."
503 lk = yield self.dec2.e.do.lk
504 if lk:
505 asmop += "l"
506 int_op = yield self.dec2.dec.op.internal_op
507 print ("int_op", int_op)
508 if int_op in [InternalOp.OP_B.value, InternalOp.OP_BC.value]:
509 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
510 print ("AA", AA)
511 if AA:
512 asmop += "a"
513 if int_op == InternalOp.OP_MFCR.value:
514 dec_insn = yield self.dec2.e.do.insn
515 if dec_insn & (1<<20) != 0: # sigh
516 asmop = 'mfocrf'
517 else:
518 asmop = 'mfcr'
519 # XXX TODO: for whatever weird reason this doesn't work
520 # https://bugs.libre-soc.org/show_bug.cgi?id=390
521 if int_op == InternalOp.OP_MTCRF.value:
522 dec_insn = yield self.dec2.e.do.insn
523 if dec_insn & (1<<20) != 0: # sigh
524 asmop = 'mtocrf'
525 else:
526 asmop = 'mtcrf'
527 return asmop
528
529 def call(self, name):
530 name = name.strip() # remove spaces if not already done so
531 if self.halted:
532 print ("halted - not executing", name)
533 return
534
535 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
536 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
537 asmop = yield from self.get_assembly_name()
538 print ("call", name, asmop)
539
540 # check halted condition
541 if name == 'attn':
542 self.halted = True
543 return
544
545 # check illegal instruction
546 illegal = False
547 if name not in ['mtcrf', 'mtocrf']:
548 illegal = name != asmop
549
550 if illegal:
551 print ("name %s != %s - calling ILLEGAL trap" % (name, asmop))
552 self.TRAP(0x700, PI.ILLEG)
553 self.namespace['NIA'] = self.trap_nia
554 self.pc.update(self.namespace)
555 return
556
557 info = self.instrs[name]
558 yield from self.prep_namespace(info.form, info.op_fields)
559
560 # preserve order of register names
561 input_names = create_args(list(info.read_regs) +
562 list(info.uninit_regs))
563 print(input_names)
564
565 # main registers (RT, RA ...)
566 inputs = []
567 for name in input_names:
568 regnum = yield getattr(self.decoder, name)
569 regname = "_" + name
570 self.namespace[regname] = regnum
571 print('reading reg %d' % regnum)
572 inputs.append(self.gpr(regnum))
573
574 # "special" registers
575 for special in info.special_regs:
576 if special in special_sprs:
577 inputs.append(self.spr[special])
578 else:
579 inputs.append(self.namespace[special])
580
581 # clear trap (trap) NIA
582 self.trap_nia = None
583
584 print(inputs)
585 results = info.func(self, *inputs)
586 print(results)
587
588 # "inject" decorator takes namespace from function locals: we need to
589 # overwrite NIA being overwritten (sigh)
590 if self.trap_nia is not None:
591 self.namespace['NIA'] = self.trap_nia
592
593 print ("after func", self.namespace['CIA'], self.namespace['NIA'])
594
595 # detect if CA/CA32 already in outputs (sra*, basically)
596 already_done = 0
597 if info.write_regs:
598 output_names = create_args(info.write_regs)
599 for name in output_names:
600 if name == 'CA':
601 already_done |= 1
602 if name == 'CA32':
603 already_done |= 2
604
605 print ("carry already done?", bin(already_done))
606 carry_en = yield self.dec2.e.do.output_carry
607 if carry_en:
608 yield from self.handle_carry_(inputs, results, already_done)
609
610 # detect if overflow was in return result
611 overflow = None
612 if info.write_regs:
613 for name, output in zip(output_names, results):
614 if name == 'overflow':
615 overflow = output
616
617 ov_en = yield self.dec2.e.do.oe.oe
618 ov_ok = yield self.dec2.e.do.oe.ok
619 print ("internal overflow", overflow)
620 if ov_en & ov_ok:
621 yield from self.handle_overflow(inputs, results, overflow)
622
623 rc_en = yield self.dec2.e.do.rc.data
624 if rc_en:
625 self.handle_comparison(results)
626
627 # any modified return results?
628 if info.write_regs:
629 for name, output in zip(output_names, results):
630 if name == 'overflow': # ignore, done already (above)
631 continue
632 if isinstance(output, int):
633 output = SelectableInt(output, 256)
634 if name in ['CA', 'CA32']:
635 if carry_en:
636 print ("writing %s to XER" % name, output)
637 self.spr['XER'][XER_bits[name]] = output.value
638 else:
639 print ("NOT writing %s to XER" % name, output)
640 elif name in info.special_regs:
641 print('writing special %s' % name, output, special_sprs)
642 if name in special_sprs:
643 self.spr[name] = output
644 else:
645 self.namespace[name].eq(output)
646 if name == 'MSR':
647 print ('msr written', hex(self.msr.value))
648 else:
649 regnum = yield getattr(self.decoder, name)
650 print('writing reg %d %s' % (regnum, str(output)))
651 if output.bits > 64:
652 output = SelectableInt(output.value, 64)
653 self.gpr[regnum] = output
654
655 print ("end of call", self.namespace['CIA'], self.namespace['NIA'])
656 # UPDATE program counter
657 self.pc.update(self.namespace)
658
659
660 def inject():
661 """Decorator factory.
662
663 this decorator will "inject" variables into the function's namespace,
664 from the *dictionary* in self.namespace. it therefore becomes possible
665 to make it look like a whole stack of variables which would otherwise
666 need "self." inserted in front of them (*and* for those variables to be
667 added to the instance) "appear" in the function.
668
669 "self.namespace['SI']" for example becomes accessible as just "SI" but
670 *only* inside the function, when decorated.
671 """
672 def variable_injector(func):
673 @wraps(func)
674 def decorator(*args, **kwargs):
675 try:
676 func_globals = func.__globals__ # Python 2.6+
677 except AttributeError:
678 func_globals = func.func_globals # Earlier versions.
679
680 context = args[0].namespace # variables to be injected
681 saved_values = func_globals.copy() # Shallow copy of dict.
682 func_globals.update(context)
683 result = func(*args, **kwargs)
684 print ("globals after", func_globals['CIA'], func_globals['NIA'])
685 print ("args[0]", args[0].namespace['CIA'],
686 args[0].namespace['NIA'])
687 args[0].namespace = func_globals
688 #exec (func.__code__, func_globals)
689
690 #finally:
691 # func_globals = saved_values # Undo changes.
692
693 return result
694
695 return decorator
696
697 return variable_injector
698