Blender  V3.3
bpy_driver.c
Go to the documentation of this file.
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 
11 #include <Python.h>
12 
13 #include "DNA_anim_types.h"
14 
15 #include "BLI_listbase.h"
16 #include "BLI_math_base.h"
17 #include "BLI_string.h"
18 
19 #include "BKE_animsys.h"
20 #include "BKE_fcurve_driver.h"
21 #include "BKE_global.h"
22 #include "BKE_idtype.h"
23 
24 #include "RNA_access.h"
25 #include "RNA_prototypes.h"
26 #include "RNA_types.h"
27 
28 #include "bpy_rna_driver.h" /* For #pyrna_driver_get_variable_value. */
29 
30 #include "bpy_intern_string.h"
31 
32 #include "bpy_driver.h"
33 #include "bpy_rna.h"
34 
35 #include "BPY_extern.h"
36 
37 #define USE_RNA_AS_PYOBJECT
38 
39 #define USE_BYTECODE_WHITELIST
40 
41 #ifdef USE_BYTECODE_WHITELIST
42 # include <opcode.h>
43 #endif
44 
45 PyObject *bpy_pydriver_Dict = NULL;
46 
47 #ifdef USE_BYTECODE_WHITELIST
49 #endif
50 
52 {
53  PyObject *d, *mod;
54 
55  /* Validate name-space for driver evaluation. */
56  if (bpy_pydriver_Dict) {
57  return -1;
58  }
59 
60  d = PyDict_New();
61  if (d == NULL) {
62  return -1;
63  }
64 
66 
67  /* Import some modules: `builtins`, `bpy`, `math`, `mathutils.noise`. */
68  PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
69 
70  mod = PyImport_ImportModule("math");
71  if (mod) {
72  PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - don't overwrite existing values */
73  Py_DECREF(mod);
74  }
75 #ifdef USE_BYTECODE_WHITELIST
76  PyObject *mod_math = mod;
77 #endif
78 
79  /* Add `bpy` to global name-space. */
80  mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
81  if (mod) {
82  PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
83  Py_DECREF(mod);
84  }
85 
86  /* Add noise to global name-space. */
87  mod = PyImport_ImportModuleLevel("mathutils", NULL, NULL, NULL, 0);
88  if (mod) {
89  PyObject *modsub = PyDict_GetItemString(PyModule_GetDict(mod), "noise");
90  PyDict_SetItemString(bpy_pydriver_Dict, "noise", modsub);
91  Py_DECREF(mod);
92  }
93 
94  /* Add math utility functions. */
95  mod = PyImport_ImportModuleLevel("bl_math", NULL, NULL, NULL, 0);
96  if (mod) {
97  static const char *names[] = {"clamp", "lerp", "smoothstep", NULL};
98 
99  for (const char **pname = names; *pname; ++pname) {
100  PyObject *func = PyDict_GetItemString(PyModule_GetDict(mod), *pname);
101  PyDict_SetItemString(bpy_pydriver_Dict, *pname, func);
102  }
103 
104  Py_DECREF(mod);
105  }
106 
107 #ifdef USE_BYTECODE_WHITELIST
108  /* Setup the whitelist. */
109  {
110  bpy_pydriver_Dict__whitelist = PyDict_New();
111  const char *whitelist[] = {
112  /* builtins (basic) */
113  "all",
114  "any",
115  "len",
116  /* builtins (numeric) */
117  "max",
118  "min",
119  "pow",
120  "round",
121  "sum",
122  /* types */
123  "bool",
124  "float",
125  "int",
126  /* bl_math */
127  "clamp",
128  "lerp",
129  "smoothstep",
130 
131  NULL,
132  };
133 
134  for (int i = 0; whitelist[i]; i++) {
135  PyDict_SetItemString(bpy_pydriver_Dict__whitelist, whitelist[i], Py_None);
136  }
137 
138  /* Add all of `math` functions. */
139  if (mod_math != NULL) {
140  PyObject *mod_math_dict = PyModule_GetDict(mod_math);
141  PyObject *arg_key, *arg_value;
142  Py_ssize_t arg_pos = 0;
143  while (PyDict_Next(mod_math_dict, &arg_pos, &arg_key, &arg_value)) {
144  const char *arg_str = PyUnicode_AsUTF8(arg_key);
145  if (arg_str[0] && arg_str[1] != '_') {
146  PyDict_SetItem(bpy_pydriver_Dict__whitelist, arg_key, Py_None);
147  }
148  }
149  }
150  }
151 #endif /* USE_BYTECODE_WHITELIST */
152 
153  return 0;
154 }
155 
160 static struct {
161  float evaltime;
162 
163  /* Borrowed reference to the `self` in `bpy_pydriver_Dict`
164  * keep for as long as the same self is used. */
165  PyObject *self;
168  .evaltime = FLT_MAX,
169  .self = NULL,
170  .depsgraph = NULL,
171 };
172 
174 {
175  if (g_pydriver_state_prev.evaltime != evaltime) {
176  PyObject *item = PyFloat_FromDouble(evaltime);
177  PyDict_SetItem(bpy_pydriver_Dict, bpy_intern_str_frame, item);
178  Py_DECREF(item);
179 
180  g_pydriver_state_prev.evaltime = evaltime;
181  }
182 }
183 
185 {
186  if ((g_pydriver_state_prev.self == NULL) ||
187  (pyrna_driver_is_equal_anim_rna(anim_rna, g_pydriver_state_prev.self) == false)) {
188  PyObject *item = pyrna_driver_self_from_anim_rna(anim_rna);
189  PyDict_SetItem(bpy_pydriver_Dict, bpy_intern_str_self, item);
190  Py_DECREF(item);
191 
192  g_pydriver_state_prev.self = item;
193  }
194 }
195 
197 {
198  if (g_pydriver_state_prev.self) {
199  PyDict_DelItem(bpy_pydriver_Dict, bpy_intern_str_self);
200 
202  }
203 }
204 
206 {
207  struct PointerRNA depsgraph_ptr;
208  RNA_pointer_create(NULL, &RNA_Depsgraph, depsgraph, &depsgraph_ptr);
209  return pyrna_struct_CreatePyObject(&depsgraph_ptr);
210 }
211 
217 {
218  /* This should never happen, but it's probably better to have None in Python
219  * than a NULL-wrapping Depsgraph Python struct. */
221  if (UNLIKELY(depsgraph == NULL)) {
222  PyDict_SetItem(bpy_pydriver_Dict, bpy_intern_str_depsgraph, Py_None);
223  g_pydriver_state_prev.depsgraph = NULL;
224  return;
225  }
226 
227  if ((g_pydriver_state_prev.depsgraph == NULL) ||
228  ((depsgraph != g_pydriver_state_prev.depsgraph->ptr.data))) {
230  PyDict_SetItem(bpy_pydriver_Dict, bpy_intern_str_depsgraph, item);
231  Py_DECREF(item);
232 
233  g_pydriver_state_prev.depsgraph = (BPy_StructRNA *)item;
234  }
235 }
236 
237 void BPY_driver_exit(void)
238 {
239  if (bpy_pydriver_Dict) { /* Free the global dict used by python-drivers. */
240  PyDict_Clear(bpy_pydriver_Dict);
241  Py_DECREF(bpy_pydriver_Dict);
243  }
244 
245 #ifdef USE_BYTECODE_WHITELIST
247  PyDict_Clear(bpy_pydriver_Dict__whitelist);
248  Py_DECREF(bpy_pydriver_Dict__whitelist);
250  }
251 #endif
252 
253  g_pydriver_state_prev.evaltime = FLT_MAX;
254 
255  /* Freed when clearing driver dictionary. */
257  g_pydriver_state_prev.depsgraph = NULL;
258 }
259 
261 {
262  PyGILState_STATE gilstate;
263  const bool use_gil = true; /* !PyC_IsInterpreterActive(); */
264 
265  if (use_gil) {
266  gilstate = PyGILState_Ensure();
267  }
268 
269  /* Currently exit/reset are practically the same besides the GIL check. */
270  BPY_driver_exit();
271 
272  if (use_gil) {
273  PyGILState_Release(gilstate);
274  }
275 }
276 
282 static void pydriver_error(ChannelDriver *driver, const struct PathResolvedRNA *anim_rna)
283 {
284  driver->flag |= DRIVER_FLAG_INVALID; /* Python expression failed. */
285 
286  const char *null_str = "<null>";
287  const ID *id = anim_rna->ptr.owner_id;
288  fprintf(stderr,
289  "\n"
290  "Error in PyDriver: expression failed: %s\n"
291  "For target: (type=%s, name=\"%s\", property=%s, property_index=%d)\n"
292  "\n",
293  driver->expression,
294  id ? BKE_idtype_idcode_to_name(GS(id->name)) : null_str,
295  id ? id->name + 2 : null_str,
296  anim_rna->prop ? RNA_property_identifier(anim_rna->prop) : null_str,
297  anim_rna->prop_index);
298 
299  // BPy_errors_to_report(NULL); /* TODO: reports. */
300  PyErr_Print();
301  PyErr_Clear();
302 }
303 
304 #ifdef USE_BYTECODE_WHITELIST
305 
306 # define OK_OP(op) [op] = true
307 
308 static const bool secure_opcodes[255] = {
309 # if PY_VERSION_HEX >= 0x030b0000 /* Python 3.11 & newer. */
310 
311  OK_OP(CACHE),
312  OK_OP(POP_TOP),
313  OK_OP(PUSH_NULL),
314  OK_OP(NOP),
315  OK_OP(UNARY_POSITIVE),
316  OK_OP(UNARY_NEGATIVE),
317  OK_OP(UNARY_NOT),
318  OK_OP(UNARY_INVERT),
319  OK_OP(BINARY_SUBSCR),
320  OK_OP(GET_LEN),
321  OK_OP(LIST_TO_TUPLE),
322  OK_OP(RETURN_VALUE),
323  OK_OP(SWAP),
324  OK_OP(BUILD_TUPLE),
325  OK_OP(BUILD_LIST),
326  OK_OP(BUILD_SET),
327  OK_OP(BUILD_MAP),
328  OK_OP(COMPARE_OP),
329  OK_OP(JUMP_FORWARD),
330  OK_OP(JUMP_IF_FALSE_OR_POP),
331  OK_OP(JUMP_IF_TRUE_OR_POP),
332  OK_OP(POP_JUMP_FORWARD_IF_FALSE),
333  OK_OP(POP_JUMP_FORWARD_IF_TRUE),
334  OK_OP(LOAD_GLOBAL),
335  OK_OP(IS_OP),
336  OK_OP(CONTAINS_OP),
337  OK_OP(BINARY_OP),
338  OK_OP(LOAD_FAST),
339  OK_OP(STORE_FAST),
340  OK_OP(DELETE_FAST),
341  OK_OP(POP_JUMP_FORWARD_IF_NOT_NONE),
342  OK_OP(POP_JUMP_FORWARD_IF_NONE),
343  OK_OP(BUILD_SLICE),
344  OK_OP(LOAD_DEREF),
345  OK_OP(STORE_DEREF),
346  OK_OP(RESUME),
347  OK_OP(LIST_EXTEND),
348  OK_OP(SET_UPDATE),
349 /* NOTE(@campbellbarton): Don't enable dict manipulation, unless we can prove there is not way it
350  * can be used to manipulate the name-space (potentially allowing malicious code). */
351 # if 0
352  OK_OP(DICT_MERGE),
353  OK_OP(DICT_UPDATE),
354 # endif
355  OK_OP(POP_JUMP_BACKWARD_IF_NOT_NONE),
356  OK_OP(POP_JUMP_BACKWARD_IF_NONE),
357  OK_OP(POP_JUMP_BACKWARD_IF_FALSE),
358  OK_OP(POP_JUMP_BACKWARD_IF_TRUE),
359 
360  /* Special cases. */
361  OK_OP(LOAD_CONST), /* Ok because constants are accepted. */
362  OK_OP(LOAD_NAME), /* Ok, because `PyCodeObject.names` is checked. */
363  OK_OP(CALL), /* Ok, because we check its "name" before calling. */
364  OK_OP(KW_NAMES), /* Ok, because it's used for calling functions with keyword arguments. */
365  OK_OP(PRECALL), /* Ok, because it's used for calling. */
366 
367 # else /* Python 3.10 and older. */
368 
369  OK_OP(POP_TOP),
370  OK_OP(ROT_TWO),
371  OK_OP(ROT_THREE),
372  OK_OP(DUP_TOP),
373  OK_OP(DUP_TOP_TWO),
374  OK_OP(ROT_FOUR),
375  OK_OP(NOP),
376  OK_OP(UNARY_POSITIVE),
377  OK_OP(UNARY_NEGATIVE),
378  OK_OP(UNARY_NOT),
379  OK_OP(UNARY_INVERT),
380  OK_OP(BINARY_MATRIX_MULTIPLY),
381  OK_OP(INPLACE_MATRIX_MULTIPLY),
382  OK_OP(BINARY_POWER),
383  OK_OP(BINARY_MULTIPLY),
384  OK_OP(BINARY_MODULO),
385  OK_OP(BINARY_ADD),
386  OK_OP(BINARY_SUBTRACT),
387  OK_OP(BINARY_SUBSCR),
388  OK_OP(BINARY_FLOOR_DIVIDE),
389  OK_OP(BINARY_TRUE_DIVIDE),
390  OK_OP(INPLACE_FLOOR_DIVIDE),
391  OK_OP(INPLACE_TRUE_DIVIDE),
392 # if PY_VERSION_HEX >= 0x030a0000 /* Python3.9 doesn't support. */
393  OK_OP(GET_LEN),
394 # endif
395  OK_OP(INPLACE_ADD),
396  OK_OP(INPLACE_SUBTRACT),
397  OK_OP(INPLACE_MULTIPLY),
398  OK_OP(INPLACE_MODULO),
399  OK_OP(BINARY_LSHIFT),
400  OK_OP(BINARY_RSHIFT),
401  OK_OP(BINARY_AND),
402  OK_OP(BINARY_XOR),
403  OK_OP(BINARY_OR),
404  OK_OP(INPLACE_POWER),
405  OK_OP(INPLACE_LSHIFT),
406  OK_OP(INPLACE_RSHIFT),
407  OK_OP(INPLACE_AND),
408  OK_OP(INPLACE_XOR),
409  OK_OP(INPLACE_OR),
410  OK_OP(LIST_TO_TUPLE),
411  OK_OP(RETURN_VALUE),
412 # if PY_VERSION_HEX >= 0x030a0000 /* Python3.9 doesn't support. */
413  OK_OP(ROT_N),
414 # endif
415  OK_OP(BUILD_TUPLE),
416  OK_OP(BUILD_LIST),
417  OK_OP(BUILD_SET),
418  OK_OP(BUILD_MAP),
419  OK_OP(COMPARE_OP),
420  OK_OP(JUMP_FORWARD),
421  OK_OP(JUMP_IF_FALSE_OR_POP),
422  OK_OP(JUMP_IF_TRUE_OR_POP),
423  OK_OP(JUMP_ABSOLUTE),
424  OK_OP(POP_JUMP_IF_FALSE),
425  OK_OP(POP_JUMP_IF_TRUE),
426  OK_OP(LOAD_GLOBAL),
427  OK_OP(IS_OP),
428  OK_OP(CONTAINS_OP),
429  OK_OP(LOAD_FAST),
430  OK_OP(STORE_FAST),
431  OK_OP(DELETE_FAST),
432  OK_OP(BUILD_SLICE),
433  OK_OP(LOAD_DEREF),
434  OK_OP(STORE_DEREF),
435  OK_OP(LIST_EXTEND),
436  OK_OP(SET_UPDATE),
437 /* NOTE(@campbellbarton): Don't enable dict manipulation, unless we can prove there is not way it
438  * can be used to manipulate the name-space (potentially allowing malicious code). */
439 # if 0
440  OK_OP(DICT_MERGE),
441  OK_OP(DICT_UPDATE),
442 # endif
443 
444  /* Special cases. */
445  OK_OP(LOAD_CONST), /* Ok because constants are accepted. */
446  OK_OP(LOAD_NAME), /* Ok, because `PyCodeObject.names` is checked. */
447  OK_OP(CALL_FUNCTION), /* Ok, because we check its "name" before calling. */
448  OK_OP(CALL_FUNCTION_KW),
449  OK_OP(CALL_FUNCTION_EX),
450 
451 # endif /* Python 3.10 and older. */
452 };
453 
454 # undef OK_OP
455 
456 bool BPY_driver_secure_bytecode_test_ex(PyObject *expr_code,
457  PyObject *namespace_array[],
458  const bool verbose,
459  const char *error_prefix)
460 {
461  PyCodeObject *py_code = (PyCodeObject *)expr_code;
462 
463  /* Check names. */
464  {
465  for (int i = 0; i < PyTuple_GET_SIZE(py_code->co_names); i++) {
466  PyObject *name = PyTuple_GET_ITEM(py_code->co_names, i);
467  const char *name_str = PyUnicode_AsUTF8(name);
468  bool contains_name = false;
469  for (int j = 0; namespace_array[j]; j++) {
470  if (PyDict_Contains(namespace_array[j], name)) {
471  contains_name = true;
472  break;
473  }
474  }
475 
476  if ((contains_name == false) || (name_str[0] == '_')) {
477  if (verbose) {
478  fprintf(stderr,
479  "\t%s: restricted access disallows name '%s', "
480  "enable auto-execution to support\n",
481  error_prefix,
482  name_str);
483  }
484  return false;
485  }
486  }
487  }
488 
489  /* Check opcodes. */
490  {
491  const _Py_CODEUNIT *codestr;
492  Py_ssize_t code_len;
493 
494  PyObject *co_code;
495 
496 # if PY_VERSION_HEX >= 0x030b0000 /* Python 3.11 & newer. */
497  co_code = PyCode_GetCode(py_code);
498  if (UNLIKELY(!co_code)) {
499  PyErr_Print();
500  PyErr_Clear();
501  return false;
502  }
503 # else
504  co_code = py_code->co_code;
505 # endif
506 
507  PyBytes_AsStringAndSize(co_code, (char **)&codestr, &code_len);
508  code_len /= sizeof(*codestr);
509  bool ok = true;
510 
511  /* Loop over op-code's, the op-code arguments are ignored. */
512  for (Py_ssize_t i = 0; i < code_len; i++) {
513  const int opcode = _Py_OPCODE(codestr[i]);
514  if (secure_opcodes[opcode] == false) {
515  if (verbose) {
516  fprintf(stderr,
517  "\t%s: restricted access disallows opcode '%d', "
518  "enable auto-execution to support\n",
519  error_prefix,
520  opcode);
521  }
522  ok = false;
523  break;
524  }
525  }
526 
527 # if PY_VERSION_HEX >= 0x030b0000 /* Python 3.11 & newer. */
528  Py_DECREF(co_code);
529 # endif
530  if (!ok) {
531  return false;
532  }
533  }
534 
535  return true;
536 }
537 
538 bool BPY_driver_secure_bytecode_test(PyObject *expr_code, PyObject *namespace, const bool verbose)
539 {
540 
541  if (!bpy_pydriver_Dict) {
542  if (bpy_pydriver_create_dict() != 0) {
543  fprintf(stderr, "%s: couldn't create Python dictionary\n", __func__);
544  return false;
545  }
546  }
547  return BPY_driver_secure_bytecode_test_ex(expr_code,
548  (PyObject *[]){
551  namespace,
552  NULL,
553  },
554  verbose,
555  __func__);
556 }
557 
558 #endif /* USE_BYTECODE_WHITELIST */
559 float BPY_driver_exec(struct PathResolvedRNA *anim_rna,
560  ChannelDriver *driver,
561  ChannelDriver *driver_orig,
562  const AnimationEvalContext *anim_eval_context)
563 {
564  /* (old) NOTE: PyGILState_Ensure() isn't always called because python can call
565  * the bake operator which intern starts a thread which calls scene update
566  * which does a driver update. to avoid a deadlock check #PyC_IsInterpreterActive()
567  * if #PyGILState_Ensure() is needed, see T27683.
568  *
569  * (new) NOTE: checking if python is running is not thread-safe T28114
570  * now release the GIL on python operator execution instead, using
571  * #PyEval_SaveThread() / #PyEval_RestoreThread() so we don't lock up blender.
572  *
573  * For copy-on-write we always cache expressions and write errors in the
574  * original driver, otherwise these would get freed while editing.
575  * Due to the GIL this is thread-safe. */
576 
577  PyObject *driver_vars = NULL;
578  PyObject *retval = NULL;
579 
580  /* Speed up by pre-hashing string & avoids re-converting unicode strings for every execution. */
581  PyObject *expr_vars;
582 
583  PyObject *expr_code;
584  PyGILState_STATE gilstate;
585  bool use_gil;
586 
587  DriverVar *dvar;
588  double result = 0.0; /* Default return. */
589  const char *expr;
590  bool targets_ok = true;
591  int i;
592 
593  /* Get the python expression to be evaluated. */
594  expr = driver_orig->expression;
595  if (expr[0] == '\0') {
596  return 0.0f;
597  }
598 
599 #ifndef USE_BYTECODE_WHITELIST
600  if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
603  BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Driver '%s'", expr);
604 
605  printf("skipping driver '%s', automatic scripts are disabled\n", expr);
606  }
607  return 0.0f;
608  }
609 #else
610  bool is_recompile = false;
611 #endif
612 
613  use_gil = true; /* !PyC_IsInterpreterActive(); */
614 
615  if (use_gil) {
616  gilstate = PyGILState_Ensure();
617  }
618 
619  /* Needed since drivers are updated directly after undo where `main` is re-allocated T28807. */
621 
622  /* Initialize global dictionary for Python driver evaluation settings. */
623  if (!bpy_pydriver_Dict) {
624  if (bpy_pydriver_create_dict() != 0) {
625  fprintf(stderr, "%s: couldn't create Python dictionary\n", __func__);
626  if (use_gil) {
627  PyGILState_Release(gilstate);
628  }
629  return 0.0f;
630  }
631  }
632 
633  /* Update global name-space. */
635 
636  if (driver_orig->flag & DRIVER_FLAG_USE_SELF) {
638  }
639  else {
641  }
642 
644 
645  if (driver_orig->expr_comp == NULL) {
646  driver_orig->flag |= DRIVER_FLAG_RECOMPILE;
647  }
648 
649  /* Compile the expression first if it hasn't been compiled or needs to be rebuilt. */
650  if (driver_orig->flag & DRIVER_FLAG_RECOMPILE) {
651  Py_XDECREF(driver_orig->expr_comp);
652  driver_orig->expr_comp = PyTuple_New(2);
653 
654  expr_code = Py_CompileString(expr, "<bpy driver>", Py_eval_input);
655  PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 0, expr_code);
656 
657  driver_orig->flag &= ~DRIVER_FLAG_RECOMPILE;
658 
659  /* Maybe this can be removed but for now best keep until were sure. */
660  driver_orig->flag |= DRIVER_FLAG_RENAMEVAR;
661 #ifdef USE_BYTECODE_WHITELIST
662  is_recompile = true;
663 #endif
664  }
665  else {
666  expr_code = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 0);
667  }
668 
669  if (driver_orig->flag & DRIVER_FLAG_RENAMEVAR) {
670  /* May not be set. */
671  expr_vars = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 1);
672  Py_XDECREF(expr_vars);
673 
674  expr_vars = PyTuple_New(BLI_listbase_count(&driver_orig->variables));
675  PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 1, expr_vars);
676 
677  for (dvar = driver_orig->variables.first, i = 0; dvar; dvar = dvar->next) {
678  PyTuple_SET_ITEM(expr_vars, i++, PyUnicode_FromString(dvar->name));
679  }
680 
681  driver_orig->flag &= ~DRIVER_FLAG_RENAMEVAR;
682  }
683  else {
684  expr_vars = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 1);
685  }
686 
687  /* Add target values to a dict that will be used as `__locals__` dict. */
688  driver_vars = _PyDict_NewPresized(PyTuple_GET_SIZE(expr_vars));
689  for (dvar = driver->variables.first, i = 0; dvar; dvar = dvar->next) {
690  PyObject *driver_arg = NULL;
691 
692  /* Support for any RNA data. */
693 #ifdef USE_RNA_AS_PYOBJECT
694  if (dvar->type == DVAR_TYPE_SINGLE_PROP) {
695  driver_arg = pyrna_driver_get_variable_value(driver, &dvar->targets[0]);
696 
697  if (driver_arg == NULL) {
698  driver_arg = PyFloat_FromDouble(0.0);
699  dvar->curval = 0.0f;
700  }
701  else {
702  /* No need to worry about overflow here, values from RNA are within limits. */
703  if (PyFloat_CheckExact(driver_arg)) {
704  dvar->curval = (float)PyFloat_AsDouble(driver_arg);
705  }
706  else if (PyLong_CheckExact(driver_arg)) {
707  dvar->curval = (float)PyLong_AsLong(driver_arg);
708  }
709  else if (PyBool_Check(driver_arg)) {
710  dvar->curval = (driver_arg == Py_True);
711  }
712  else {
713  dvar->curval = 0.0f;
714  }
715  }
716  }
717  else
718 #endif
719  {
720  /* Try to get variable value. */
721  const float tval = driver_get_variable_value(driver, dvar);
722  driver_arg = PyFloat_FromDouble((double)tval);
723  }
724 
725  /* Try to add to dictionary. */
726  /* `if (PyDict_SetItemString(driver_vars, dvar->name, driver_arg)) {` */
727  if (PyDict_SetItem(driver_vars, PyTuple_GET_ITEM(expr_vars, i++), driver_arg) != -1) {
728  /* Pass. */
729  }
730  else {
731  /* This target failed - bad name. */
732  if (targets_ok) {
733  /* First one, print some extra info for easier identification. */
734  fprintf(stderr, "\n%s: Error while evaluating PyDriver:\n", __func__);
735  targets_ok = false;
736  }
737 
738  fprintf(stderr, "\t%s: couldn't add variable '%s' to namespace\n", __func__, dvar->name);
739  // BPy_errors_to_report(NULL); /* TODO: reports. */
740  PyErr_Print();
741  PyErr_Clear();
742  }
743  Py_DECREF(driver_arg);
744  }
745 
746 #ifdef USE_BYTECODE_WHITELIST
747  if (is_recompile && expr_code) {
748  if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
750  expr_code,
751  (PyObject *[]){
754  driver_vars,
755  NULL,
756  },
757  /* Always be verbose since this can give hints to why evaluation fails. */
758  true,
759  __func__)) {
762  BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Driver '%s'", expr);
763  }
764 
765  Py_DECREF(expr_code);
766  expr_code = NULL;
767  PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 0, NULL);
768  }
769  }
770  }
771 #endif /* USE_BYTECODE_WHITELIST */
772 
773 #if 0 /* slow, with this can avoid all Py_CompileString above. */
774  /* execute expression to get a value */
775  retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
776 #else
777  /* Evaluate the compiled expression. */
778  if (expr_code) {
779  retval = PyEval_EvalCode((void *)expr_code, bpy_pydriver_Dict, driver_vars);
780  }
781 #endif
782 
783  /* Decref the driver variables first. */
784  Py_DECREF(driver_vars);
785 
786  /* Process the result. */
787  if (retval == NULL) {
788  pydriver_error(driver, anim_rna);
789  }
790  else {
791  if (UNLIKELY((result = PyFloat_AsDouble(retval)) == -1.0 && PyErr_Occurred())) {
792  pydriver_error(driver, anim_rna);
793  result = 0.0;
794  }
795  else {
796  /* All fine, make sure the "invalid expression" flag is cleared. */
797  driver->flag &= ~DRIVER_FLAG_INVALID;
798  }
799  Py_DECREF(retval);
800  }
801 
802  if (use_gil) {
803  PyGILState_Release(gilstate);
804  }
805 
806  if (UNLIKELY(!isfinite(result))) {
807  fprintf(stderr, "\t%s: driver '%s' evaluates to '%f'\n", __func__, driver->expression, result);
808  return 0.0f;
809  }
810 
811  return (float)result;
812 }
typedef float(TangentPoint)[2]
float driver_get_variable_value(struct ChannelDriver *driver, struct DriverVar *dvar)
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET
Definition: BKE_global.h:158
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL
Definition: BKE_global.h:157
@ G_FLAG_SCRIPT_AUTOEXEC
Definition: BKE_global.h:154
const char * BKE_idtype_idcode_to_name(short idcode)
Definition: idtype.c:142
#define BLI_assert(a)
Definition: BLI_assert.h:46
int BLI_listbase_count(const struct ListBase *listbase) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
size_t BLI_snprintf(char *__restrict dst, size_t maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
#define SWAP(type, a, b)
#define UNLIKELY(x)
struct Depsgraph Depsgraph
Definition: DEG_depsgraph.h:35
@ DVAR_TYPE_SINGLE_PROP
@ DRIVER_FLAG_INVALID
@ DRIVER_FLAG_RECOMPILE
@ DRIVER_FLAG_USE_SELF
@ DRIVER_FLAG_RENAMEVAR
_GL_VOID GLfloat value _GL_VOID_RET _GL_VOID const GLuint GLboolean *residences _GL_BOOL_RET _GL_VOID GLsizei GLfloat GLfloat GLfloat GLfloat const GLubyte *bitmap _GL_VOID_RET _GL_VOID GLenum const void *lists _GL_VOID_RET _GL_VOID const GLdouble *equation _GL_VOID_RET _GL_VOID GLdouble GLdouble blue _GL_VOID_RET _GL_VOID GLfloat GLfloat blue _GL_VOID_RET _GL_VOID GLint GLint blue _GL_VOID_RET _GL_VOID GLshort GLshort blue _GL_VOID_RET _GL_VOID GLubyte GLubyte blue _GL_VOID_RET _GL_VOID GLuint GLuint blue _GL_VOID_RET _GL_VOID GLushort GLushort blue _GL_VOID_RET _GL_VOID GLbyte GLbyte GLbyte alpha _GL_VOID_RET _GL_VOID GLdouble GLdouble GLdouble alpha _GL_VOID_RET _GL_VOID GLfloat GLfloat GLfloat alpha _GL_VOID_RET _GL_VOID GLint GLint GLint alpha _GL_VOID_RET _GL_VOID GLshort GLshort GLshort alpha _GL_VOID_RET _GL_VOID GLubyte GLubyte GLubyte alpha _GL_VOID_RET _GL_VOID GLuint GLuint GLuint alpha _GL_VOID_RET _GL_VOID GLushort GLushort GLushort alpha _GL_VOID_RET _GL_VOID GLenum mode _GL_VOID_RET _GL_VOID GLint GLsizei GLsizei GLenum type _GL_VOID_RET _GL_VOID GLsizei GLenum GLenum const void *pixels _GL_VOID_RET _GL_VOID const void *pointer _GL_VOID_RET _GL_VOID GLdouble v _GL_VOID_RET _GL_VOID GLfloat v _GL_VOID_RET _GL_VOID GLint GLint i2 _GL_VOID_RET _GL_VOID GLint j _GL_VOID_RET _GL_VOID GLfloat param _GL_VOID_RET _GL_VOID GLint param _GL_VOID_RET _GL_VOID GLdouble GLdouble GLdouble GLdouble GLdouble zFar _GL_VOID_RET _GL_UINT GLdouble *equation _GL_VOID_RET _GL_VOID GLenum pname
#define arg_str(...)
Definition: bgl.c:365
static PyObject * bpy_pydriver_Dict__whitelist
Definition: bpy_driver.c:48
static struct @1157 g_pydriver_state_prev
bool BPY_driver_secure_bytecode_test(PyObject *expr_code, PyObject *namespace, const bool verbose)
Definition: bpy_driver.c:538
PyObject * bpy_pydriver_Dict
Definition: bpy_driver.c:45
static void pydriver_error(ChannelDriver *driver, const struct PathResolvedRNA *anim_rna)
Definition: bpy_driver.c:282
float evaltime
Definition: bpy_driver.c:161
static void bpy_pydriver_namespace_update_depsgraph(struct Depsgraph *depsgraph)
Definition: bpy_driver.c:216
BPy_StructRNA * depsgraph
Definition: bpy_driver.c:166
static void bpy_pydriver_namespace_update_frame(const float evaltime)
Definition: bpy_driver.c:173
static void bpy_pydriver_namespace_clear_self(void)
Definition: bpy_driver.c:196
void BPY_driver_exit(void)
Definition: bpy_driver.c:237
void BPY_driver_reset(void)
Definition: bpy_driver.c:260
#define OK_OP(op)
Definition: bpy_driver.c:306
static PyObject * bpy_pydriver_depsgraph_as_pyobject(struct Depsgraph *depsgraph)
Definition: bpy_driver.c:205
int bpy_pydriver_create_dict(void)
Definition: bpy_driver.c:51
static const bool secure_opcodes[255]
Definition: bpy_driver.c:308
bool BPY_driver_secure_bytecode_test_ex(PyObject *expr_code, PyObject *namespace_array[], const bool verbose, const char *error_prefix)
Definition: bpy_driver.c:456
static void bpy_pydriver_namespace_update_self(struct PathResolvedRNA *anim_rna)
Definition: bpy_driver.c:184
float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, ChannelDriver *driver_orig, const AnimationEvalContext *anim_eval_context)
Definition: bpy_driver.c:559
PyObject * bpy_intern_str_depsgraph
PyObject * bpy_intern_str_self
PyObject * bpy_intern_str_frame
PyObject * pyrna_struct_CreatePyObject(PointerRNA *ptr)
Definition: bpy_rna.c:7505
void BPY_update_rna_module(void)
Definition: bpy_rna.c:7762
PyObject * pyrna_driver_self_from_anim_rna(PathResolvedRNA *anim_rna)
PyObject * pyrna_driver_get_variable_value(struct ChannelDriver *driver, struct DriverTarget *dtar)
bool pyrna_driver_is_equal_anim_rna(const PathResolvedRNA *anim_rna, const PyObject *py_anim_rna)
static int verbose
Definition: cineonlib.c:29
#define GS(x)
Definition: iris.c:225
static char ** names
Definition: makesdna.c:65
#define G(x, y, z)
bool isfinite(uchar)
Definition: scene/image.cpp:31
void RNA_pointer_create(ID *id, StructRNA *type, void *data, PointerRNA *r_ptr)
Definition: rna_access.c:136
const char * RNA_property_identifier(const PropertyRNA *prop)
Definition: rna_access.c:1000
#define CALL(member, value_str)
struct Depsgraph * depsgraph
Definition: BKE_animsys.h:42
ListBase variables
char expression[256]
struct DriverVar * next
DriverTarget targets[8]
char name[64]
Definition: DNA_ID.h:368
char name[66]
Definition: DNA_ID.h:378
void * first
Definition: DNA_listBase.h:31
struct PropertyRNA * prop
Definition: RNA_types.h:51
struct PointerRNA ptr
Definition: RNA_types.h:50
struct ID * owner_id
Definition: RNA_types.h:36
ccl_device_inline int mod(int x, int m)
Definition: util/math.h:490