aboutsummaryrefslogtreecommitdiff
path: root/gcc/testsuite/gcc.dg/plugin/analyzer_gil_plugin.c
blob: 57135fc59043a997e5d043f937d026edc07e91cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/* Proof-of-concept of a -fanalyzer plugin.
   Detect (some) uses of CPython API outside of the Global Interpreter Lock.
   https://docs.python.org/3/c-api/init.html#thread-state-and-the-global-interpreter-lock
*/
/* { dg-options "-g" } */

#define INCLUDE_MEMORY
#define INCLUDE_VECTOR
#include "gcc-plugin.h"
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "make-unique.h"
#include "diagnostic.h"
#include "tree.h"
#include "gimple.h"
#include "gimple-iterator.h"
#include "gimple-walk.h"
#include "diagnostic-event-id.h"
#include "analyzer/analyzer.h"
#include "analyzer/analyzer-logging.h"
#include "json.h"
#include "analyzer/sm.h"
#include "analyzer/pending-diagnostic.h"

int plugin_is_GPL_compatible;

#if ENABLE_ANALYZER

namespace ana {

static bool
type_based_on_pyobject_p (tree type)
{
  /* Ideally we'd also check for "subclasses" here by iterating up the
     first field of each struct.  */
  if (TREE_CODE (type) != RECORD_TYPE)
    return false;
  tree name = TYPE_IDENTIFIER (type);
  if (!name)
    return false;
  return id_equal (name, "PyObject");
}

/* An experimental state machine, for tracking whether the GIL is held,
   as global state..  */

class gil_state_machine : public state_machine
{
public:
  gil_state_machine (logger *logger);

  bool inherited_state_p () const final override { return false; }

  bool on_stmt (sm_context *sm_ctxt,
		const supernode *node,
		const gimple *stmt) const final override;

  bool can_purge_p (state_t s) const final override;

  void check_for_pyobject_usage_without_gil (sm_context *sm_ctxt,
					     const supernode *node,
					     const gimple *stmt,
					     tree op) const;

 private:
  void check_for_pyobject_in_call (sm_context *sm_ctxt,
				   const supernode *node,
				   const gcall *call,
				   tree callee_fndecl) const;

 public:
  /* These states are "global", rather than per-expression.  */

  /* State for when we've released the GIL.  */
  state_t m_released_gil;

  /* Stop state.  */
  state_t m_stop;
};

/* Subclass for diagnostics involving the GIL.  */

class gil_diagnostic : public pending_diagnostic
{
public:
  /* There isn't a warning ID for us to use.  */
  int get_controlling_option () const final override
  {
    return 0;
  }

  location_t fixup_location (location_t loc,
			     bool) const final override
  {
    /* Ideally we'd check for specific macros here, and only
       resolve certain macros.  */
    if (linemap_location_from_macro_expansion_p (line_table, loc))
      loc = linemap_resolve_location (line_table, loc,
				      LRK_MACRO_EXPANSION_POINT, NULL);
    return loc;
  }

  label_text describe_state_change (const evdesc::state_change &change)
    final override
  {
    if (change.is_global_p ()
	&& change.m_new_state == m_sm.m_released_gil)
      return change.formatted_print ("releasing the GIL here");
    if (change.is_global_p ()
	&& change.m_new_state == m_sm.get_start_state ())
      return change.formatted_print ("acquiring the GIL here");
    return label_text ();
  }

  diagnostic_event::meaning
  get_meaning_for_state_change (const evdesc::state_change &change)
    const final override
  {
    if (change.is_global_p ())
      {
	if (change.m_new_state == m_sm.m_released_gil)
	  return diagnostic_event::meaning (diagnostic_event::VERB_release,
					    diagnostic_event::NOUN_lock);
	else if (change.m_new_state == m_sm.get_start_state ())
	  return diagnostic_event::meaning (diagnostic_event::VERB_acquire,
					    diagnostic_event::NOUN_lock);
      }
    return diagnostic_event::meaning ();
  }
 protected:
  gil_diagnostic (const gil_state_machine &sm) : m_sm (sm)
  {
  }

 private:
  const gil_state_machine &m_sm;
};

class double_save_thread : public gil_diagnostic
{
 public:
  double_save_thread (const gil_state_machine &sm, const gcall *call)
  : gil_diagnostic (sm), m_call (call)
  {}

  const char *get_kind () const final override
  {
    return "double_save_thread";
  }

  bool subclass_equal_p (const pending_diagnostic &base_other) const override
  {
    const double_save_thread &sub_other
      = (const double_save_thread &)base_other;
    return m_call == sub_other.m_call;
  }

  bool emit (diagnostic_emission_context &ctxt) final override
  {
    return ctxt.warn ("nested usage of %qs", "Py_BEGIN_ALLOW_THREADS");
  }

  label_text describe_final_event (const evdesc::final_event &ev) final override
  {
    return ev.formatted_print ("nested usage of %qs here",
			       "Py_BEGIN_ALLOW_THREADS");
  }

 private:
  const gcall *m_call;
};

class fncall_without_gil : public gil_diagnostic
{
 public:
  fncall_without_gil (const gil_state_machine &sm, const gcall *call,
		      tree callee_fndecl, unsigned arg_idx)
  : gil_diagnostic (sm), m_call (call), m_callee_fndecl (callee_fndecl),
    m_arg_idx (arg_idx)
  {}

  const char *get_kind () const final override
  {
    return "fncall_without_gil";
  }

  bool subclass_equal_p (const pending_diagnostic &base_other) const override
  {
    const fncall_without_gil &sub_other
      = (const fncall_without_gil &)base_other;
    return (m_call == sub_other.m_call
	    && m_callee_fndecl == sub_other.m_callee_fndecl
	    && m_arg_idx == sub_other.m_arg_idx);
  }

  bool emit (diagnostic_emission_context &ctxt) final override
  {
    if (m_callee_fndecl)
      return ctxt.warn ("use of PyObject as argument %i of %qE"
			" without the GIL",
			m_arg_idx + 1, m_callee_fndecl);
    else
      return ctxt.warn ("use of PyObject as argument %i of call"
			" without the GIL",
			m_arg_idx + 1, m_callee_fndecl);
  }

  label_text describe_final_event (const evdesc::final_event &ev) final override
  {
    if (m_callee_fndecl)
      return ev.formatted_print ("use of PyObject as argument %i of %qE here"
				 " without the GIL",
				 m_arg_idx + 1, m_callee_fndecl);
    else
      return ev.formatted_print ("use of PyObject as argument %i of call here"
				 " without the GIL",
				 m_arg_idx + 1, m_callee_fndecl);
  }

 private:
  const gcall *m_call;
  tree m_callee_fndecl;
  unsigned m_arg_idx;
};

class pyobject_usage_without_gil : public gil_diagnostic
{
 public:
  pyobject_usage_without_gil (const gil_state_machine &sm, tree expr)
  : gil_diagnostic (sm), m_expr (expr)
  {}

  const char *get_kind () const final override
  {
    return "pyobject_usage_without_gil";
  }

  bool subclass_equal_p (const pending_diagnostic &base_other) const override
  {
    return same_tree_p (m_expr,
			((const pyobject_usage_without_gil&)base_other).m_expr);
  }

  bool emit (diagnostic_emission_context &ctxt) final override
  {
    return ctxt.warn ("use of PyObject %qE without the GIL", m_expr);
  }

  label_text describe_final_event (const evdesc::final_event &ev) final override
  {
    return ev.formatted_print ("PyObject %qE used here without the GIL",
			       m_expr);
  }

 private:
  tree m_expr;
};

/* gil_state_machine's ctor.  */

gil_state_machine::gil_state_machine (logger *logger)
: state_machine ("gil", logger)
{
  m_released_gil = add_state ("released_gil");
  m_stop = add_state ("stop");
}

struct cb_data
{
  cb_data (const gil_state_machine &sm, sm_context *sm_ctxt,
	   const supernode *snode, const gimple *stmt)
  : m_sm (sm), m_sm_ctxt (sm_ctxt), m_snode (snode), m_stmt (stmt)
  {
  }

  const gil_state_machine &m_sm;
  sm_context *m_sm_ctxt;
  const supernode *m_snode;
  const gimple *m_stmt;
};

static bool
check_for_pyobject (gimple *, tree op, tree, void *data)
{
  cb_data *d = (cb_data *)data;
  d->m_sm.check_for_pyobject_usage_without_gil (d->m_sm_ctxt, d->m_snode,
						d->m_stmt, op);
  return true;
}

/* Assuming that the GIL has been released, complain about any
   PyObject * arguments passed to CALL.  */

void
gil_state_machine::check_for_pyobject_in_call (sm_context *sm_ctxt,
					       const supernode *node,
					       const gcall *call,
					       tree callee_fndecl) const
{
  for (unsigned i = 0; i < gimple_call_num_args (call); i++)
    {
      tree arg = gimple_call_arg (call, i);
      if (TREE_CODE (TREE_TYPE (arg)) != POINTER_TYPE)
	continue;
      tree type = TREE_TYPE (TREE_TYPE (arg));
      if (type_based_on_pyobject_p (type))
	{
	  sm_ctxt->warn (node, call, NULL_TREE,
			 make_unique<fncall_without_gil> (*this, call,
							  callee_fndecl,
							  i));
	  sm_ctxt->set_global_state (m_stop);
	}
    }
}

/* Implementation of state_machine::on_stmt vfunc for gil_state_machine.  */

bool
gil_state_machine::on_stmt (sm_context *sm_ctxt,
			    const supernode *node,
			    const gimple *stmt) const
{
  const state_t global_state = sm_ctxt->get_global_state ();
  if (const gcall *call = dyn_cast <const gcall *> (stmt))
    {
      if (tree callee_fndecl = sm_ctxt->get_fndecl_for_call (call))
	{
	  if (is_named_call_p (callee_fndecl, "PyEval_SaveThread", call, 0))
	    {
	      if (0)
		inform (input_location, "found call to %qs",
			"PyEval_SaveThread");
	      if (global_state == m_released_gil)
		{
		  sm_ctxt->warn (node, stmt, NULL_TREE,
				 make_unique<double_save_thread> (*this, call));
		  sm_ctxt->set_global_state (m_stop);
		}
	      else
		sm_ctxt->set_global_state (m_released_gil);
	      return true;
	    }
	  else if (is_named_call_p (callee_fndecl, "PyEval_RestoreThread",
				    call, 1))
	    {
	      if (0)
		inform (input_location, "found call to %qs",
			"PyEval_SaveThread");
	      if (global_state == m_released_gil)
		sm_ctxt->set_global_state (m_start);
	      return true;
	    }
	  else if (global_state == m_released_gil)
	    {
	      /* Find PyObject * args of calls to fns with unknown bodies.  */
	      if (!fndecl_has_gimple_body_p (callee_fndecl))
		check_for_pyobject_in_call (sm_ctxt, node, call, callee_fndecl);
	    }
	}
      else if (global_state == m_released_gil)
	check_for_pyobject_in_call (sm_ctxt, node, call, NULL);
    }
  else
    if (global_state == m_released_gil)
      {
	/* Walk the stmt, finding uses of PyObject (or "subclasses").  */
	cb_data d (*this, sm_ctxt, node, stmt);
	walk_stmt_load_store_addr_ops (const_cast <gimple *> (stmt), &d,
				       check_for_pyobject,
				       check_for_pyobject,
				       check_for_pyobject);
    }
  return false;
}

bool
gil_state_machine::can_purge_p (state_t s ATTRIBUTE_UNUSED) const
{
  return true;
}

void
gil_state_machine::check_for_pyobject_usage_without_gil (sm_context *sm_ctxt,
							 const supernode *node,
							 const gimple *stmt,
							 tree op) const
{
  tree type = TREE_TYPE (op);
  if (type_based_on_pyobject_p (type))
    {
      sm_ctxt->warn (node, stmt, NULL_TREE,
		     make_unique<pyobject_usage_without_gil> (*this, op));
      sm_ctxt->set_global_state (m_stop);
    }
}

/* Callback handler for the PLUGIN_ANALYZER_INIT event.  */

static void
gil_analyzer_init_cb (void *gcc_data, void */*user_data*/)
{
  ana::plugin_analyzer_init_iface *iface
    = (ana::plugin_analyzer_init_iface *)gcc_data;
  LOG_SCOPE (iface->get_logger ());
  if (0)
    inform (input_location, "got here: gil_analyzer_init_cb");
  iface->register_state_machine
    (make_unique<gil_state_machine> (iface->get_logger ()));
}

} // namespace ana

#endif /* #if ENABLE_ANALYZER */

int
plugin_init (struct plugin_name_args *plugin_info,
	     struct plugin_gcc_version *version)
{
#if ENABLE_ANALYZER
  const char *plugin_name = plugin_info->base_name;
  if (0)
    inform (input_location, "got here; %qs", plugin_name);
  register_callback (plugin_info->base_name,
		     PLUGIN_ANALYZER_INIT,
		     ana::gil_analyzer_init_cb,
		     NULL); /* void *user_data */
#else
  sorry_no_analyzer ();
#endif
  return 0;
}