• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef JNI_ZERO_JNI_WRAPPERS_H_
6 #define JNI_ZERO_JNI_WRAPPERS_H_
7 
8 #include <jni.h>
9 
10 #include <iterator>
11 #include <string_view>
12 
13 #include "third_party/jni_zero/java_refs.h"
14 #include "third_party/jni_zero/logging.h"
15 
16 // Wrapper used to receive int when calling Java from native.
17 // The wrapper disallows automatic conversion of long to int.
18 // This is to avoid a common anti-pattern where a Java int is used
19 // to receive a native pointer. Please use a Java long to receive
20 // native pointers, so that the code works on both 32-bit and 64-bit
21 // platforms. Note the wrapper allows other lossy conversions into
22 // jint that could be consider anti-patterns, such as from size_t.
23 
24 // Checking is only done in debugging builds.
25 
26 #ifdef NDEBUG
27 
28 typedef jint JniIntWrapper;
29 
30 // This inline is sufficiently trivial that it does not change the
31 // final code generated by g++.
as_jint(JniIntWrapper wrapper)32 inline jint as_jint(JniIntWrapper wrapper) {
33   return wrapper;
34 }
35 
36 #else
37 
38 class JniIntWrapper {
39  public:
JniIntWrapper()40   JniIntWrapper() : i_(0) {}
JniIntWrapper(int i)41   JniIntWrapper(int i) : i_(i) {}
JniIntWrapper(const JniIntWrapper & ji)42   JniIntWrapper(const JniIntWrapper& ji) : i_(ji.i_) {}
43   template <class T>
JniIntWrapper(const T & t)44   JniIntWrapper(const T& t) : i_(t) {}
as_jint()45   jint as_jint() const { return i_; }
46 
47  private:
48   // If you get an "is private" error at the line below it is because you used
49   // an implicit conversion to convert a long to an int when calling Java.
50   // We disallow this, as a common anti-pattern allows converting a native
51   // pointer (intptr_t) to a Java int. Please use a Java long to represent
52   // a native pointer. If you want a lossy conversion, please use an
53   // explicit conversion in your C++ code. Note an error is only seen when
54   // compiling on a 64-bit platform, as intptr_t is indistinguishable from
55   // int on 32-bit platforms.
56   JniIntWrapper(long);
57   jint i_;
58 };
59 
as_jint(const JniIntWrapper & wrapper)60 inline jint as_jint(const JniIntWrapper& wrapper) {
61   return wrapper.as_jint();
62 }
63 
64 #endif  // NDEBUG
65 
66 namespace jni_zero {
67 // Wrapper for a jobjectArray which supports input iteration, allowing Java
68 // arrays to be iterated over with a range-based for loop, or used with
69 // <algorithm> functions that accept input iterators.
70 //
71 // The iterator returns each object in the array in turn, wrapped in a
72 // ScopedJavaLocalRef<T>. T will usually be jobject, but if you know that the
73 // array contains a more specific type (such as jstring) you can use that
74 // instead. This does not check the type at runtime!
75 //
76 // The wrapper holds a local reference to the array and only queries the size of
77 // the array once, so must only be used as a stack-based object from the current
78 // thread.
79 //
80 // Note that this does *not* update the contents of the array if you mutate the
81 // returned ScopedJavaLocalRef.
82 template <typename T>
83 class JavaObjectArrayReader {
84  public:
85   class iterator {
86    public:
87     // We can only be an input iterator, as all richer iterator types must
88     // implement the multipass guarantee (always returning the same object for
89     // the same iterator position), which is not practical when returning
90     // temporary objects.
91     using iterator_category = std::input_iterator_tag;
92 
93     using difference_type = ptrdiff_t;
94     using value_type = ScopedJavaLocalRef<T>;
95 
96     // It doesn't make sense to return a reference type as the iterator creates
97     // temporary wrapper objects when dereferenced. Fortunately, it's not
98     // required that input iterators actually use references, and defining it
99     // as value_type is valid.
100     using reference = value_type;
101 
102     // This exists to make operator-> work as expected: its return value must
103     // resolve to an actual pointer (otherwise the compiler just keeps calling
104     // operator-> on the return value until it does), so we need an extra level
105     // of indirection. This is sometimes called an "arrow proxy" or similar, and
106     // this version is adapted from base/value_iterators.h.
107     class pointer {
108      public:
pointer(const reference & ref)109       explicit pointer(const reference& ref) : ref_(ref) {}
110       pointer(const pointer& ptr) = default;
111       pointer& operator=(const pointer& ptr) = delete;
112       reference* operator->() { return &ref_; }
113 
114      private:
115       reference ref_;
116     };
117 
118     iterator(const iterator&) = default;
119     ~iterator() = default;
120 
121     iterator& operator=(const iterator&) = default;
122 
123     bool operator==(const iterator& other) const {
124       JNI_ZERO_DCHECK(reader_ == other.reader_);
125       return i_ == other.i_;
126     }
127 
128     bool operator!=(const iterator& other) const {
129       JNI_ZERO_DCHECK(reader_ == other.reader_);
130       return i_ != other.i_;
131     }
132 
133     reference operator*() const {
134       JNI_ZERO_DCHECK(i_ < reader_->size_);
135       // JNIEnv functions return unowned local references; take ownership with
136       // Adopt so that ~ScopedJavaLocalRef will release it automatically later.
137       return value_type::Adopt(
138           reader_->array_.env_,
139           static_cast<T>(reader_->array_.env_->GetObjectArrayElement(
140               reader_->array_.obj(), i_)));
141     }
142 
143     pointer operator->() const { return pointer(operator*()); }
144 
145     iterator& operator++() {
146       JNI_ZERO_DCHECK(i_ < reader_->size_);
147       ++i_;
148       return *this;
149     }
150 
151     iterator operator++(int) {
152       iterator old = *this;
153       ++*this;
154       return old;
155     }
156 
157    private:
iterator(const JavaObjectArrayReader * reader,jsize i)158     iterator(const JavaObjectArrayReader* reader, jsize i)
159         : reader_(reader), i_(i) {}
160     const JavaObjectArrayReader<T>* reader_;
161     jsize i_;
162 
163     friend JavaObjectArrayReader;
164   };
165 
JavaObjectArrayReader(const JavaRef<jobjectArray> & array)166   JavaObjectArrayReader(const JavaRef<jobjectArray>& array) : array_(array) {
167     size_ = array_.env_->GetArrayLength(array_.obj());
168   }
169 
170   // Copy constructor to allow returning it from JavaRef::ReadElements().
171   JavaObjectArrayReader(const JavaObjectArrayReader& other) = default;
172 
173   // Assignment operator for consistency with copy constructor.
174   JavaObjectArrayReader& operator=(const JavaObjectArrayReader& other) =
175       default;
176 
177   // Allow move constructor and assignment since this owns a local ref.
178   JavaObjectArrayReader(JavaObjectArrayReader&& other) = default;
179   JavaObjectArrayReader& operator=(JavaObjectArrayReader&& other) = default;
180 
empty()181   bool empty() const { return size_ == 0; }
182 
size()183   jsize size() const { return size_; }
184 
begin()185   iterator begin() const { return iterator(this, 0); }
186 
end()187   iterator end() const { return iterator(this, size_); }
188 
189  private:
190   ScopedJavaLocalRef<jobjectArray> array_;
191   jsize size_;
192 
193   friend iterator;
194 };
195 
196 // Use as: @JniType("jni_zero::ByteArrayView") byte[].
197 //
198 // This requests a direct pointer to the array data rather than a copy of it,
199 // so can be more efficient than std::vector<uint8_t> for large arrays.
200 //
201 // This helper needs to release the array via its destructor, and as a result
202 // has more binary size overhead than using std::vector<uint8_t>. As such, you
203 // should prefer std::vector for small arrays.
204 //
205 // Callers must ensure that the passed in array reference outlives this wrapper
206 // (always the case when used with @JniType).
207 class ByteArrayView {
208  public:
ByteArrayView(JNIEnv * env,jbyteArray array)209   ByteArrayView(JNIEnv* env, jbyteArray array)
210       : env_(env),
211         array_(array),
212         length_(env->GetArrayLength(array)),
213         bytes_(env->GetByteArrayElements(array, nullptr)) {}
214 
~ByteArrayView()215   ~ByteArrayView() {
216     env_->ReleaseByteArrayElements(array_, bytes_, JNI_ABORT);
217   }
218 
219   ByteArrayView(const ByteArrayView&) = delete;
220   ByteArrayView(ByteArrayView&& other) = delete;
221   ByteArrayView& operator=(const ByteArrayView&) = delete;
222 
size()223   size_t size() const { return static_cast<size_t>(length_); }
empty()224   bool empty() const { return length_ == 0; }
bytes()225   const jbyte* bytes() const { return bytes_; }
data()226   const uint8_t* data() const { return reinterpret_cast<uint8_t*>(bytes_); }
chars()227   const char* chars() const { return reinterpret_cast<char*>(bytes_); }
string_view()228   std::string_view string_view() const {
229     return std::string_view(chars(), size());
230   }
231 
232  private:
233   JNIEnv* env_;
234   jbyteArray array_;
235   jsize length_;
236   jbyte* bytes_;
237 };
238 
239 }  // namespace jni_zero
240 
241 #endif  // JNI_ZERO_JNI_WRAPPERS_H_
242