hooks_py.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "hooks_py.h"
  2. #include "simulator.h"
  3. #include "core_manager.h"
  4. #include "config.hpp"
  5. #include "fxsupport.h"
  6. bool HooksPy::pyInit = false;
  7. void HooksPy::init()
  8. {
  9. UInt64 numscripts = Sim()->getCfg()->getInt("hooks/numscripts");
  10. for(UInt64 i = 0; i < numscripts; ++i) {
  11. String scriptname = Sim()->getCfg()->getString(String("hooks/script") + itostr(i) + "name");
  12. if (scriptname.substr(scriptname.length()-3) == ".py") {
  13. if (! pyInit) {
  14. setup();
  15. }
  16. String args = Sim()->getCfg()->getString(String("hooks/script") + itostr(i) + "args");
  17. char *argv[] = { (char*)(scriptname.c_str()), (char*)(args.c_str()) };
  18. PySys_SetArgvEx(2, argv, 0 /* updatepath */);
  19. printf("Executing Python script %s\n", scriptname.c_str());
  20. int s = PyRun_SimpleFileEx(fopen(scriptname.c_str(), "r"), scriptname.c_str(), 1 /* closeit */);
  21. if (s != 0) {
  22. PyErr_Print();
  23. fprintf(stderr, "Cannot open Python script %s\n", scriptname.c_str());
  24. exit(-1);
  25. }
  26. }
  27. }
  28. }
  29. void HooksPy::setup()
  30. {
  31. pyInit = true;
  32. const char* sim_root = NULL;
  33. const char env_roots[2][16] = {"SNIPER_ROOT", "GRAPHITE_ROOT"};
  34. for (unsigned int i = 0 ; i < 2 ; i++)
  35. {
  36. sim_root = getenv(env_roots[i]);
  37. if (sim_root)
  38. break;
  39. }
  40. LOG_ASSERT_ERROR(sim_root, "Please make sure SNIPER_ROOT or GRAPHITE_ROOT is set");
  41. #ifdef TARGET_INTEL64
  42. String python_home = String(sim_root) + "/python_kit/intel64";
  43. #else
  44. String python_home = String(sim_root) + "/python_kit/ia32";
  45. #endif
  46. Py_SetPythonHome(strdup(python_home.c_str()));
  47. Py_InitializeEx(0 /* don't initialize signal handlers */);
  48. // set up all components
  49. PyConfig::setup();
  50. PyStats::setup();
  51. PyHooks::setup();
  52. PyDvfs::setup();
  53. PyControl::setup();
  54. PyBbv::setup();
  55. PyMem::setup();
  56. PyThread::setup();
  57. }
  58. void HooksPy::fini()
  59. {
  60. if (pyInit)
  61. Py_Finalize();
  62. }
  63. PyObject * HooksPy::callPythonFunction(PyObject *pFunc, PyObject *pArgs)
  64. {
  65. PyObject *pResult = PyObject_CallObject(pFunc, pArgs);
  66. Py_XDECREF(pArgs);
  67. if (pResult == NULL) {
  68. PyErr_Print();
  69. }
  70. return pResult;
  71. }