1 : /*
2 : * Copyright (c) 2011 The Native Client Authors. All rights reserved.
3 : * Use of this source code is governed by a BSD-style license that can be
4 : * found in the LICENSE file.
5 : */
6 :
7 : #include "native_client/src/shared/platform/refcount_base.h"
8 :
9 : #include "native_client/src/include/portability.h" // NACL_PRIxPTR etc
10 : #include "native_client/src/shared/platform/nacl_log.h"
11 : #include "native_client/src/shared/platform/nacl_check.h"
12 :
13 : namespace nacl {
14 :
15 10 : RefCountBase::RefCountBase() : refcount_(1) {
16 10 : if (!NaClMutexCtor(&mu_)) {
17 0 : NaClLog(LOG_FATAL, "scoped_ptr_refcount_obj: could not create mutex\n");
18 0 : }
19 10 : }
20 :
21 : RefCountBase* RefCountBase::Ref() {
22 5 : NaClXMutexLock(&mu_);
23 5 : if (0 == ++refcount_) {
24 0 : NaClLog(LOG_FATAL,
25 : ("scoped_ptr_refcount_obj: refcount overflow on 0x%08"
26 : NACL_PRIxPTR "\n"),
27 : reinterpret_cast<uintptr_t>(this));
28 0 : }
29 5 : NaClXMutexUnlock(&mu_);
30 5 : return this;
31 : }
32 :
33 : void RefCountBase::Unref() {
34 5 : NaClXMutexLock(&mu_);
35 5 : if (0 == refcount_) {
36 0 : NaClLog(LOG_FATAL,
37 : ("scoped_ptr_refcount_obj: Unref on zero refcount object: "
38 : "0x%08" NACL_PRIxPTR "\n"),
39 : reinterpret_cast<uintptr_t>(this));
40 0 : }
41 5 : bool do_delete = (0 == --refcount_);
42 5 : NaClXMutexUnlock(&mu_);
43 5 : if (do_delete) {
44 10 : delete this;
45 5 : }
46 5 : }
47 :
48 5 : RefCountBase::~RefCountBase() {
49 15 : CHECK(refcount_ == 0);
50 5 : NaClMutexDtor(&mu_);
51 : // Unlike in our src/trusted/nacl_base/nacl_refcount.h C code where
52 : // our ctor could fail and subclass ctors that fail must dtor the
53 : // base class object, in C++ the ctor must succeed. Thus, the dtor
54 : // cannot possible encounter a count_==1 object, since that
55 : // situation only occurred when during ctor failure induced,
56 : // explicit dtor calls.
57 5 : }
58 :
59 : } // namespace nacl
|