1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // Object.cpp: Defines the Object base class that provides
16 // lifecycle support for GL objects using the traditional BindObject scheme, but
17 // that need to be reference counted for correct cross-context deletion.
18 
19 #include "Object.hpp"
20 
21 #include "Common/Thread.hpp"
22 
23 namespace gl
24 {
25 #ifndef NDEBUG
26 std::set<Object*> Object::instances;
27 #endif
28 
Object()29 Object::Object()
30 {
31 	referenceCount = 0;
32 
33 	#ifndef NDEBUG
34 		instances.insert(this);
35 	#endif
36 }
37 
~Object()38 Object::~Object()
39 {
40 	ASSERT(referenceCount == 0);
41 
42 	#ifndef NDEBUG
43 		ASSERT(instances.find(this) != instances.end());   // Check for double deletion
44 		instances.erase(this);
45 	#endif
46 }
47 
addRef()48 void Object::addRef()
49 {
50 	sw::atomicIncrement(&referenceCount);
51 }
52 
release()53 void Object::release()
54 {
55 	if(dereference() == 0)
56 	{
57 		delete this;
58 	}
59 }
60 
dereference()61 int Object::dereference()
62 {
63 	ASSERT(referenceCount > 0);
64 
65 	if(referenceCount > 0)
66 	{
67 		return sw::atomicDecrement(&referenceCount);
68 	}
69 
70 	return 0;
71 }
72 
destroy()73 void Object::destroy()
74 {
75 	referenceCount = 0;
76 	delete this;
77 }
78 
NamedObject(GLuint name)79 NamedObject::NamedObject(GLuint name) : name(name)
80 {
81 }
82 
~NamedObject()83 NamedObject::~NamedObject()
84 {
85 }
86 
87 #ifndef NDEBUG
88 struct ObjectLeakCheck
89 {
~ObjectLeakCheckgl::ObjectLeakCheck90 	~ObjectLeakCheck()
91 	{
92 		ASSERT(Object::instances.empty());   // Check for GL object leak at termination
93 	}
94 };
95 
96 static ObjectLeakCheck objectLeakCheck;
97 #endif
98 
99 }
100