summaryrefslogtreecommitdiffstats
path: root/xbmc/interfaces/legacy/CallbackHandler.cpp
blob: f5671688c4b5580bd1524424cf70319a3f0212b8 (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
/*
 *  Copyright (C) 2005-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "CallbackHandler.h"

#include "AddonUtils.h"
#include "commons/Exception.h"
#include "utils/log.h"

#include <mutex>
#include <vector>

namespace XBMCAddon
{
  class AsyncCallbackMessage : public AddonClass
  {
  public:
    AddonClass::Ref<Callback> cb;
    AddonClass::Ref<RetardedAsyncCallbackHandler> handler;
    AsyncCallbackMessage(Callback* _cb, RetardedAsyncCallbackHandler* _handler) :
      cb(_cb), handler(_handler) { XBMC_TRACE; }
  };

  //********************************************************************
  // This holds the callback messages which will be executed. It doesn't
  //  seem to work correctly with the Ref object so we'll go with Ref*'s
  typedef std::vector<AddonClass::Ref<AsyncCallbackMessage> > CallbackQueue;
  //********************************************************************

  static CCriticalSection critSection;
  static CallbackQueue g_callQueue;

  void RetardedAsyncCallbackHandler::invokeCallback(Callback* cb)
  {
    XBMC_TRACE;
    std::unique_lock<CCriticalSection> lock(critSection);
    g_callQueue.push_back(new AsyncCallbackMessage(cb,this));
  }

  RetardedAsyncCallbackHandler::~RetardedAsyncCallbackHandler()
  {
    XBMC_TRACE;
    std::unique_lock<CCriticalSection> lock(critSection);

    // find any messages that might be there because of me ... and remove them
    CallbackQueue::iterator iter = g_callQueue.begin();
    while (iter != g_callQueue.end())
    {
      if ((*iter)->handler.get() == this) // then this message is because of me
      {
        g_callQueue.erase(iter);
        iter = g_callQueue.begin();
      }
      else
        ++iter;
    }
  }

  void RetardedAsyncCallbackHandler::makePendingCalls()
  {
    XBMC_TRACE;
    std::unique_lock<CCriticalSection> lock(critSection);
    CallbackQueue::iterator iter = g_callQueue.begin();
    while (iter != g_callQueue.end())
    {
      AddonClass::Ref<AsyncCallbackMessage> p(*iter);

      // only call when we are in the right thread state
      if(p->handler->isStateOk(p->cb->getObject()))
      {
        // remove it from the queue. No matter what we're done with
        //  this. Even if it doesn't execute for some reason.
        g_callQueue.erase(iter);

        // we need to release the critSection lock prior to grabbing the
        //  lock on the object. Not doing so results in deadlocks. We no
        //  longer are accessing the g_callQueue so it's fine to do this now
        {
          XBMCAddonUtils::InvertSingleLockGuard unlock(lock);

          // make sure the object is not deallocating

          // we need to grab the object lock to see if the object of the call
          //  is deallocating. holding this lock should prevent it from
          //  deallocating during the execution of this call.
#ifdef ENABLE_XBMC_TRACE_API
          CLog::Log(LOGDEBUG, "{}NEWADDON executing callback 0x{:x}", _tg.getSpaces(),
                    (long)(p->cb.get()));
#endif
          AddonClass* obj = (p->cb->getObject());
          AddonClass::Ref<AddonClass> ref(obj);
          std::unique_lock<CCriticalSection> lock2(*obj);
          if (!p->cb->getObject()->isDeallocating())
          {
            try
            {
              // need to make the call
              p->cb->executeCallback();
            }
            catch (XbmcCommons::Exception& e) { e.LogThrowMessage(); }
            catch (...)
            {
              CLog::Log(LOGERROR, "Unknown exception while executing callback {:#x}",
                        reinterpret_cast<int64_t>(p->cb.get()));
            }
          }
        }

        // since the state of the iterator may have been corrupted by
        //  the changing state of the list from another thread during
        //  the releasing fo the lock in the immediately preceeding
        //  codeblock, we need to reset it before continuing the loop
        iter = g_callQueue.begin();
      }
      else // if we're not in the right thread for this callback...
        ++iter;
    }
  }

  void RetardedAsyncCallbackHandler::clearPendingCalls(void* userData)
  {
    XBMC_TRACE;
    std::unique_lock<CCriticalSection> lock(critSection);
    CallbackQueue::iterator iter = g_callQueue.begin();
    while (iter != g_callQueue.end())
    {
      AddonClass::Ref<AsyncCallbackMessage> p(*iter);

      if(p->handler->shouldRemoveCallback(p->cb->getObject(),userData))
      {
#ifdef ENABLE_XBMC_TRACE_API
        CLog::Log(LOGDEBUG,
                  "{}NEWADDON removing callback 0x{:x} for PyThreadState 0x{:x} from queue",
                  _tg.getSpaces(), (long)(p->cb.get()), (long)userData);
#endif
        iter = g_callQueue.erase(iter);
      }
      else
        ++iter;
    }
  }
}