HAL  v4.5.0-299-g9ee015483
The Hardware Analyzer - a comprehensive reverse engineering and manipulation framework for gate-level netlists.
python_bindings.cpp
Go to the documentation of this file.
1 // MIT License
2 //
3 // Copyright (c) 2019 Ruhr University Bochum, Chair for Embedded Security. All Rights reserved.
4 // Copyright (c) 2019 Marc Fyrbiak, Sebastian Wallat, Max Hoffmann ("ORIGINAL AUTHORS"). All rights reserved.
5 // Copyright (c) 2021 Max Planck Institute for Security and Privacy. All Rights reserved.
6 // Copyright (c) 2021 Jörn Langheinrich, Julian Speith, Nils Albartus, René Walendy, Simon Klix ("ORIGINAL AUTHORS"). All Rights reserved.
7 // Copyright (c) 2025-2026 Sascha Tommasone. All rights reserved.
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
15 //
16 // The above copyright notice and this permission notice shall be included in all
17 // copies or substantial portions of the Software.
18 //
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 // SOFTWARE.
26 
28 
33 #include "pybind11/pybind11.h"
34 #include "pybind11/stl.h"
35 
36 #include <igraph/igraph.h>
37 #include <optional>
38 #include <pybind11/pytypes.h>
39 #include <set>
40 #include <string>
41 #include <vector>
42 
43 namespace hal
44 {
45  class BasePluginInterface;
46 }
47 namespace hal
48 {
49  class Netlist;
50 }
51 
52 namespace py = pybind11;
53 
54 namespace hal
55 {
56 
57  // the name in PYBIND11_MODULE/PYBIND11_PLUGIN *MUST* match the filename of the output library (without extension),
58  // otherwise you will get "ImportError: dynamic module does not define module export function" when importing the
59  // module
60 
61 #ifdef PYBIND11_MODULE
62  PYBIND11_MODULE( clock_tree_extractor, m )
63  {
64  m.doc() = "";
65 #else
66  PYBIND11_PLUGIN( clock_tree_extractor )
67  {
68  py::module m( "clock_tree_extractor", "" );
69 #endif // ifdef PYBIND11_MODULE
70 
71  py::class_<ClockTreeExtractorPlugin, RawPtrWrapper<ClockTreeExtractorPlugin>, BasePluginInterface>
72  py_clock_tree_extractor_plugin( m, "ClockTreeExtractorPlugin", "" );
73 
74  py_clock_tree_extractor_plugin.def_property_readonly( "name", &ClockTreeExtractorPlugin::get_name, R"(
75  The name of the plugin.
76 
77  :type: str
78  )" );
79 
80  py_clock_tree_extractor_plugin.def( "get_name", &ClockTreeExtractorPlugin::get_name, R"(
81  Get the name of the plugin.
82 
83  :returns: The name of the plugin.
84  :rtype: str
85  )" );
86 
87  py_clock_tree_extractor_plugin.def_property_readonly( "version", &ClockTreeExtractorPlugin::get_version, R"(
88  The version of the plugin.
89 
90  :type: str
91  )" );
92 
93  py_clock_tree_extractor_plugin.def( "get_version", &ClockTreeExtractorPlugin::get_version, R"(
94  Get the version of the plugin.
95 
96  :returns: The version of the plugin.
97  :rtype: str
98  )" );
99 
100  py_clock_tree_extractor_plugin.def_property_readonly(
101  "description", &ClockTreeExtractorPlugin::get_description, R"(
102  The description of the plugin.
103 
104  :type: str
105  )" );
106 
107  py_clock_tree_extractor_plugin.def( "get_description", &ClockTreeExtractorPlugin::get_description, R"(
108  Get the description of the plugin.
109 
110  :returns: The description of the plugin.
111  :rtype: str
112  )" );
113 
114  py_clock_tree_extractor_plugin.def_property_readonly(
115  "dependencies", &ClockTreeExtractorPlugin::get_dependencies, R"(
116  A set of plugin names that this plugin depends on.
117 
118  :type: set[str]
119  )" );
120 
121  py_clock_tree_extractor_plugin.def( "get_dependencies", &ClockTreeExtractorPlugin::get_dependencies, R"(
122  Get a set of plugin names that this plugin depends on.
123 
124  :returns: A set of plugin names that this plugin depends on.
125  :rtype: set[str]
126  )" );
127 
128  py::enum_<cte::PtrType>( m, "PtrType", R"(
129  The kind of object a clock tree vertex or diagnostic refers to.
130  )" )
131  .value( "UNKNOWN", cte::PtrType::UNKNOWN )
132  .value( "GATE", cte::PtrType::GATE )
133  .value( "NET", cte::PtrType::NET )
134  .export_values();
135 
136  py::enum_<cte::Severity>( m, "Severity", R"(
137  The severity of a diagnostic emitted during clock tree extraction.
138  )" )
139  .value( "warning", cte::Severity::warning )
140  .value( "error", cte::Severity::error );
141 
142  py::enum_<cte::DiagnosticCode>( m, "DiagnosticCode", R"(
143  The machine-readable kind of a diagnostic emitted during clock tree extraction.
144  )" )
145  .value( "invalid_clock_pin_count", cte::DiagnosticCode::invalid_clock_pin_count )
146  .value( "unconnected_clock_pin", cte::DiagnosticCode::unconnected_clock_pin )
147  .value( "invalid_clock_net_sources", cte::DiagnosticCode::invalid_clock_net_sources )
148  .value( "unrouted_clock_net", cte::DiagnosticCode::unrouted_clock_net )
149  .value( "multi_driven_clock_net", cte::DiagnosticCode::multi_driven_clock_net );
150 
151  py::class_<cte::Diagnostic>( m, "Diagnostic", R"(
152  A problem encountered during clock tree extraction, e.g., a gate or net that had to be skipped.
153  )" )
154  .def_readonly( "severity", &cte::Diagnostic::severity, R"(
155  The severity.
156 
157  :type: clock_tree_extractor.Severity
158  )" )
159  .def_readonly( "code", &cte::Diagnostic::code, R"(
160  The machine-readable kind of the diagnostic.
161 
162  :type: clock_tree_extractor.DiagnosticCode
163  )" )
164  .def_readonly( "subject_type", &cte::Diagnostic::subject_type, R"(
165  Whether the subject is a gate or a net.
166 
167  :type: clock_tree_extractor.PtrType
168  )" )
169  .def_property_readonly(
170  "ptr",
171  []( const cte::Diagnostic &self ) -> py::object {
172  if( self.subject_type == cte::PtrType::GATE )
173  {
174  return py::cast( (const Gate *) self.subject_ptr );
175  }
176  else if( self.subject_type == cte::PtrType::NET )
177  {
178  return py::cast( (const Net *) self.subject_ptr );
179  }
180  return py::none();
181  },
182  borrowed(),
183  R"(
184  The gate or net the diagnostic is about.
185 
186  :type: hal_py.Gate or hal_py.Net or None
187  )" )
188  .def_readonly( "subject_id", &cte::Diagnostic::subject_id, R"(
189  The ID of the gate or net the diagnostic is about.
190 
191  :type: int
192  )" )
193  .def_readonly( "message", &cte::Diagnostic::message, R"(
194  The human-readable message.
195 
196  :type: str
197  )" );
198 
199  py::class_<cte::ClockTree>( m, "ClockTree", R"(
200  The clock distribution network of a netlist as a directed graph whose vertices are gates and nets.
201  )" )
202  .def_static(
203  "from_netlist",
204  []( const Netlist *netlist ) -> std::unique_ptr<cte::ClockTree> {
205  auto result = cte::ClockTree::from_netlist( netlist );
206  if( result.is_ok() )
207  {
208  return result.get();
209  }
210 
211  log_error( "clock_tree_extractor", "{}", result.get_error().get() );
212  return nullptr;
213  },
214  py::arg( "netlist" ),
215  py::return_value_policy::move,
216  py::keep_alive<0, 1>(),
217  R"(
218  Extract the clock tree of a netlist.
219 
220  Starting at the clock pin of every flip-flop, the extraction walks against the signal direction through buffers, inverters, delay gates, clock gates and toggle flip-flops up to the global input nets that drive them.
221 
222  :param hal_py.Netlist netlist: The netlist.
223  :returns: The clock tree on success, ``None`` otherwise.
224  :rtype: clock_tree_extractor.ClockTree or None
225  )" )
226  .def(
227  "export",
228  []( const cte::ClockTree &self,
229  const std::string &pathname,
230  const std::optional<std::string> &x_key,
231  const std::optional<std::string> &y_key ) -> bool {
232  auto result = cte::export_dot( self, pathname, x_key, y_key );
233  if( result.is_ok() )
234  {
235  return true;
236  }
237 
238  log_error( "clock_tree_extractor", "{}", result.get_error().get() );
239  return false;
240  },
241  py::arg( "pathname" ),
242  py::arg( "x_key" ) = py::none(),
243  py::arg( "y_key" ) = py::none(),
244  R"(
245  Write the clock tree to a DOT file. Gates get the coordinates of their location in the layout, unless the
246  keys of both coordinates are given: then they are read from the gate parameters of these names, e.g.,
247  from Verilog instance parameters, which unlike a location can be negative.
248 
249  :param str pathname: The path of the file to write.
250  :param str x_key: The name of the parameter that holds the x-coordinate, or ``None`` to use the location.
251  :param str y_key: The name of the parameter that holds the y-coordinate, or ``None`` to use the location.
252  :returns: ``True`` on success, ``False`` otherwise.
253  :rtype: bool
254  )" )
255  .def(
256  "get_subtree",
257  []( const cte::ClockTree &self,
258  const void *ptr,
259  const bool parent ) -> std::unique_ptr<cte::ClockTree> {
260  auto result = self.get_subtree( ptr, parent );
261  if( result.is_ok() )
262  {
263  return result.get();
264  }
265 
266  log_error( "clock_tree_extractor", "{}", result.get_error().get() );
267  return nullptr;
268  },
269  py::arg( "ptr" ),
270  py::arg( "parent" ) = false,
271  py::return_value_policy::move,
272  py::keep_alive<0, 1>(),
273  R"(
274  Get the clock tree below a gate or net as a clock tree of its own.
275 
276  :param ptr: The gate or net.
277  :type ptr: hal_py.Gate or hal_py.Net
278  :param bool parent: Set ``True`` to start one level up, at the parent of the given object, if it has exactly one. Defaults to ``False``.
279  :returns: The subtree on success, ``None`` otherwise.
280  :rtype: clock_tree_extractor.ClockTree or None
281  )" )
282  .def(
283  "get_all",
284  []( const cte::ClockTree &self ) -> py::list {
285  py::list result;
286  const auto &map = self.get_all();
287  for( auto &[ptr, type] : map )
288  {
289  if( type == cte::PtrType::GATE )
290  {
291  result.append( py::cast( (const Gate *) ptr ) );
292  }
293  else if( type == cte::PtrType::NET )
294  {
295  result.append( py::cast( (const Net *) ptr ) );
296  }
297  }
298  return result;
299  },
300  borrowed(),
301  R"(
302  Get all gates and nets of the clock tree.
303 
304  :returns: A list of gates and nets.
305  :rtype: list[hal_py.Gate or hal_py.Net]
306  )" )
307  .def(
308  "get_vertex_from_ptr",
309  []( const cte::ClockTree &self, const void *ptr ) -> py::object {
310  auto result = self.get_vertex_from_ptr( ptr );
311  if( result.is_ok() )
312  {
313  return py::int_( result.get() );
314  }
315  log_error( "clock_tree_extractor", "{}", result.get_error().get() );
316  return py::none();
317  },
318  py::arg( "ptr" ),
319  R"(
320  Get the igraph vertex ID of a gate or net of the clock tree.
321 
322  :param ptr: The gate or net.
323  :type ptr: hal_py.Gate or hal_py.Net
324  :returns: The vertex ID on success, ``None`` otherwise.
325  :rtype: int or None
326  )" )
327  .def(
328  "get_ptr_from_vertex",
329  []( const cte::ClockTree &self, const igraph_int_t vertex ) -> py::object {
330  auto result = self.get_ptr_from_vertex( vertex );
331  if( result.is_ok() )
332  {
333  auto [ptr, type] = result.get();
334  if( type == cte::PtrType::GATE )
335  {
336  return py::cast( (const Gate *) ptr );
337  }
338  else if( type == cte::PtrType::NET )
339  {
340  return py::cast( (const Net *) ptr );
341  }
342  return py::none();
343  }
344  log_error( "clock_tree_extractor", "{}", result.get_error().get() );
345  return py::none();
346  },
347  py::arg( "vertex" ),
348  borrowed(),
349  R"(
350  Get the gate or net behind an igraph vertex ID of the clock tree.
351 
352  :param int vertex: The vertex ID.
353  :returns: The gate or net on success, ``None`` otherwise.
354  :rtype: hal_py.Gate or hal_py.Net or None
355  )" )
356  .def(
357  "get_vertices_from_ptrs",
358  []( const cte::ClockTree &self, const std::vector<const void *> &ptrs ) -> py::list {
359  auto result = self.get_vertices_from_ptrs( ptrs );
360  if( result.is_ok() )
361  {
362  return py::cast( result.get() );
363  }
364  log_error( "clock_tree_extractor", "{}", result.get_error().get() );
365  return py::none();
366  },
367  py::arg( "ptrs" ),
368  R"(
369  Get the igraph vertex IDs of gates and nets of the clock tree.
370 
371  :param list[hal_py.Gate or hal_py.Net] ptrs: The gates and nets.
372  :returns: The vertex IDs on success, ``None`` otherwise.
373  :rtype: list[int] or None
374  )" )
375  .def(
376  "get_ptrs_from_vertices",
377  []( const cte::ClockTree &self, const std::vector<igraph_int_t> &vertices ) -> py::list {
378  auto res = self.get_ptrs_from_vertices( vertices );
379  if( res.is_ok() )
380  {
381  py::list result;
382  for( const auto &[ptr, type] : res.get() )
383  {
384  if( type == cte::PtrType::GATE )
385  {
386  result.append( py::cast( (const Gate *) ptr ) );
387  }
388  else if( type == cte::PtrType::NET )
389  {
390  result.append( py::cast( (const Net *) ptr ) );
391  }
392  else
393  {
394  log_error( "clock_tree_extractor", "unknown ptr type" );
395  return py::none();
396  }
397  }
398  return result;
399  }
400  log_error( "clock_tree_extractor", "{}", res.get_error().get() );
401  return py::none();
402  },
403  py::arg( "vertices" ),
404  borrowed(),
405  R"(
406  Get the gates and nets behind igraph vertex IDs of the clock tree.
407 
408  :param list[int] vertices: The vertex IDs.
409  :returns: The gates and nets on success, ``None`` otherwise.
410  :rtype: list[hal_py.Gate or hal_py.Net] or None
411  )" )
412  .def(
413  "get_parents",
414  []( const cte::ClockTree &self, const void *ptr ) -> py::list {
415  auto res = self.get_neighbors( ptr, IGRAPH_IN );
416  if( res.is_ok() )
417  {
418  py::list result;
419  for( const auto &[ptr, type] : res.get() )
420  {
421  if( type == cte::PtrType::GATE )
422  {
423  result.append( py::cast( (const Gate *) ptr ) );
424  }
425  else if( type == cte::PtrType::NET )
426  {
427  result.append( py::cast( (const Net *) ptr ) );
428  }
429  else
430  {
431  log_error( "clock_tree_extractor", "unknown ptr type" );
432  return py::none();
433  }
434  }
435  return result;
436  }
437  log_error( "clock_tree_extractor", "{}", res.get_error().get() );
438  return py::none();
439  },
440  py::arg( "ptr" ),
441  borrowed(),
442  R"(
443  Get the gates and nets directly upstream of a gate or net in the clock tree.
444 
445  :param ptr: The gate or net.
446  :type ptr: hal_py.Gate or hal_py.Net
447  :returns: The neighbors on success, ``None`` otherwise.
448  :rtype: list[hal_py.Gate or hal_py.Net] or None
449  )" )
450  .def(
451  "get_childs",
452  []( const cte::ClockTree &self, const void *ptr ) -> py::list {
453  auto res = self.get_neighbors( ptr, IGRAPH_OUT );
454  if( res.is_ok() )
455  {
456  py::list result;
457  for( const auto &[ptr, type] : res.get() )
458  {
459  if( type == cte::PtrType::GATE )
460  {
461  result.append( py::cast( (const Gate *) ptr ) );
462  }
463  else if( type == cte::PtrType::NET )
464  {
465  result.append( py::cast( (const Net *) ptr ) );
466  }
467  else
468  {
469  log_error( "clock_tree_extractor", "unknown ptr type" );
470  return py::none();
471  }
472  }
473  return result;
474  }
475  log_error( "clock_tree_extractor", "{}", res.get_error().get() );
476  return py::none();
477  },
478  py::arg( "ptr" ),
479  borrowed(),
480  R"(
481  Get the gates and nets directly downstream of a gate or net in the clock tree.
482 
483  :param ptr: The gate or net.
484  :type ptr: hal_py.Gate or hal_py.Net
485  :returns: The neighbors on success, ``None`` otherwise.
486  :rtype: list[hal_py.Gate or hal_py.Net] or None
487  )" )
488  .def( "get_gates", &cte::ClockTree::get_gates, borrowed(), R"(
489  Get all gates of the clock tree.
490 
491  :returns: The gates.
492  :rtype: list[hal_py.Gate]
493  )" )
494  .def( "get_nets", &cte::ClockTree::get_nets, borrowed(), R"(
495  Get all nets of the clock tree.
496 
497  :returns: The nets.
498  :rtype: list[hal_py.Net]
499  )" )
500  .def( "get_netlist", &cte::ClockTree::get_netlist, borrowed(), R"(
501  Get the netlist the clock tree was extracted from.
502 
503  :returns: The netlist.
504  :rtype: hal_py.Netlist
505  )" )
506  .def( "get_diagnostics", &cte::ClockTree::get_diagnostics, R"(
507  Get the diagnostics collected while the clock tree was recovered. Empty for subtrees.
508 
509  :returns: The diagnostics.
510  :rtype: list[clock_tree_extractor.Diagnostic]
511  )" )
512  .def(
513  "get_branches",
514  []( const cte::ClockTree &self ) -> py::object {
515  auto res = cte::recover_branches( self );
516  if( res.is_error() )
517  {
518  log_error( "clock_tree_extractor", "{}", res.get_error().get() );
519  return py::none();
520  }
521 
522  py::list branches;
523  for( const auto &branch : res.get() )
524  {
525  py::list py_branch;
526  for( const auto &[ptr, type] : branch )
527  {
528  if( type == cte::PtrType::GATE )
529  {
530  py_branch.append( py::cast( (const Gate *) ptr ) );
531  }
532  else if( type == cte::PtrType::NET )
533  {
534  py_branch.append( py::cast( (const Net *) ptr ) );
535  }
536  else
537  {
538  log_error( "clock_tree_extractor", "unknown ptr type" );
539  return py::none();
540  }
541  }
542  branches.append( std::move( py_branch ) );
543  }
544  return std::move( branches );
545  },
546  borrowed(),
547  R"(
548  Get all branches of the clock tree, i.e., all paths from a root to a sink. The branches are recomputed on every call.
549 
550  :returns: The branches on success, ``None`` otherwise. Each branch is ordered from root to sink.
551  :rtype: list[list[hal_py.Gate or hal_py.Net]] or None
552  )" );
553 
554 #ifndef PYBIND11_MODULE
555  return m.ptr();
556 #endif // PYBIND11_MODULE
557  }
558 } // namespace hal
std::string get_description() const override
std::string get_name() const override
std::set< std::string > get_dependencies() const override
std::string get_version() const override
Definition: gate.h:59
Definition: net.h:58
std::vector< const Gate * > get_gates() const
Definition: clock_tree.cpp:679
const Netlist * get_netlist() const
Definition: clock_tree.cpp:714
std::vector< const Net * > get_nets() const
Definition: clock_tree.cpp:694
const std::vector< Diagnostic > & get_diagnostics() const
Definition: clock_tree.cpp:719
static Result< std::unique_ptr< ClockTree > > from_netlist(const Netlist *netlist)
Definition: clock_tree.cpp:158
#define log_error(channel,...)
Definition: log.h:78
const Module * module(const Gate *g, const NodeBoxes &boxes)
Result< std::vector< Branch > > recover_branches(const ClockTree &clock_tree)
Definition: branches.cpp:78
Result< std::monostate > export_dot(const ClockTree &clock_tree, const std::string &pathname, const std::optional< std::string > &x_key=std::nullopt, const std::optional< std::string > &y_key=std::nullopt)
Definition: dot_export.cpp:93
Definition: defines.h:45
PYBIND11_PLUGIN(hal_py)
PinType type
std::string message
Definition: clock_tree.h:67
DiagnosticCode code
Definition: clock_tree.h:63