-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcrt.c
More file actions
835 lines (696 loc) · 29 KB
/
crt.c
File metadata and controls
835 lines (696 loc) · 29 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/auth/auth.h>
#include <aws/common/allocator.h>
#include <aws/common/atomics.h>
#include <aws/common/clock.h>
#include <aws/common/common.h>
#include <aws/common/hash_table.h>
#include <aws/common/logging.h>
#include <aws/common/rw_lock.h>
#include <aws/common/string.h>
#include <aws/common/system_info.h>
#include <aws/common/thread.h>
#include <aws/event-stream/event_stream.h>
#include <aws/http/connection.h>
#include <aws/http/http.h>
#include <aws/io/channel.h>
#include <aws/io/io.h>
#include <aws/io/logging.h>
#include <aws/io/tls_channel_handler.h>
#include <aws/mqtt/mqtt.h>
#include <aws/s3/s3.h>
#include "crt.h"
#include "java_class_ids.h"
#include "logging.h"
#include <stdio.h>
#ifdef AWS_OS_LINUX
# include <openssl/crypto.h>
#endif
/* 0 = off, 1 = bytes, 2 = stack traces, see aws_mem_trace_level */
int g_memory_tracing = 0;
int g_crt_fips_mode = 0;
static struct aws_allocator *s_init_allocator(void) {
if (g_memory_tracing) {
struct aws_allocator *allocator = aws_default_allocator();
allocator = aws_mem_tracer_new(allocator, NULL, (enum aws_mem_trace_level)g_memory_tracing, 8);
return allocator;
}
return aws_default_allocator();
}
static struct aws_allocator *s_allocator = NULL;
struct aws_allocator *aws_jni_get_allocator(void) {
if (AWS_UNLIKELY(s_allocator == NULL)) {
s_allocator = s_init_allocator();
}
return s_allocator;
}
/*
Dispatch queue threads are handled differently than other types as we do not create and manage them. This is set during
creation of an Event Loop Group to control attach/detach to/from JVM behavior of threads.
*/
static bool s_dispatch_queue_threads = false;
void aws_jni_set_dispatch_queue_threads(bool is_dispatch_queue) {
s_dispatch_queue_threads = is_dispatch_queue;
}
static void s_detach_jvm_from_thread(void *user_data) {
AWS_LOGF_DEBUG(AWS_LS_COMMON_GENERAL, "s_detach_jvm_from_thread invoked");
JavaVM *jvm = user_data;
/* we don't need this JNIEnv, but this is an easy way to verify the JVM is still valid to use */
/********** JNI ENV ACQUIRE **********/
struct aws_jvm_env_context jvm_env_context = aws_jni_acquire_thread_env(jvm);
if (jvm_env_context.env != NULL) {
(*jvm)->DetachCurrentThread(jvm);
aws_jni_release_thread_env(jvm, &jvm_env_context);
/********** JNI ENV RELEASE **********/
}
}
static struct aws_jvm_env_context s_aws_jni_get_thread_env(JavaVM *jvm) {
struct aws_jvm_env_context jvm_env_context = {.env = NULL, .should_detach = false};
if ((*jvm)->GetEnv(jvm, (void **)&jvm_env_context.env, JNI_VERSION_1_6) == JNI_EDETACHED) {
if (!s_dispatch_queue_threads) {
AWS_LOGF_DEBUG(AWS_LS_COMMON_GENERAL, "s_aws_jni_get_thread_env returned detached, attaching");
}
struct aws_string *thread_name = NULL;
if (aws_thread_current_name(aws_jni_get_allocator(), &thread_name)) {
/* Retrieving thread name can fail for multitude of reasons and is
not fatal. Ignore the error and continue. */
AWS_LOGF_DEBUG(AWS_LS_COMMON_GENERAL, "Failed to retrieve name for the thread.");
}
struct JavaVMAttachArgs attach_args = {
.version = JNI_VERSION_1_6,
.name = NULL,
.group = NULL,
};
if (thread_name != NULL) {
attach_args.name = (char *)aws_string_c_str(thread_name);
}
#ifdef ANDROID
jint result = (*jvm)->AttachCurrentThreadAsDaemon(jvm, &jvm_env_context.env, &attach_args);
#else
jint result = (*jvm)->AttachCurrentThreadAsDaemon(jvm, (void **)&jvm_env_context.env, &attach_args);
#endif
aws_string_destroy(thread_name);
/* Ran out of memory, don't log in this case */
AWS_FATAL_ASSERT(result != JNI_ENOMEM);
if (result != JNI_OK) {
fprintf(stderr, "Unrecoverable AttachCurrentThreadAsDaemon failed, JNI error code is %d\n", (int)result);
jvm_env_context.env = NULL;
return jvm_env_context;
}
jvm_env_context.should_detach = true;
/*
Dispatch Queue threads are managed by Apple's GCD and thus can't have an at_exit callback assigned. We manually
detatch dispatch queue threads from the JVM during `aws_jni_release_thread_env()` to insure cleanup.
*/
if (!s_dispatch_queue_threads) {
/* This should only happen in event loop threads, the JVM main thread attachment is
* managed by the JVM, so we only need to clean up event loop thread attachments */
AWS_FATAL_ASSERT(AWS_OP_SUCCESS == aws_thread_current_at_exit(s_detach_jvm_from_thread, (void *)jvm));
}
}
return jvm_env_context;
}
/*
A simple system to support unpredictable JVM shutdowns. In an ideal world, everyone would correctly use the
CrtResource ref counting and strict (aws_thread_managed_join_all) shutdown, but given the difficulty of using
them correctly, that's not a realistic expectation. So we need to come up with a way for JVM shutdowns to
not trigger crashes from native threads that try and call back to Java (where even the JavaVM pointer cached
on the binding object is now garbage) after the JVM has shutdown (but before the process has killed all of its
threads).
Our system works as follows:
We track the set of all active JVMs (since we don't correctly support multiple JVMs yet, this is always going to be
either one or zero for now). We protect this set with a read-write lock. Adding (CRT init) or removing (JVM
shutdown hook) a JVM from this set will take a write lock. Acquiring a JNIEnv from a tracked JVM, will take a read
lock, and releasing a JNIEnv will release the read lock.
Acquiring a JNIEnv succeeds if the JVM in question is in our set, and fails otherwise. All users of a JNIEnv have
been hardened to check for null and just not call to Java in that case.
Since we don't have RAII in C, bindings must be very careful to release once, and exactly once, every JNIEnv that
they acquire. An alternative approach would be to replace all of the JNIEnv usage with a new API that
takes the lock, calls a supplied callback (which does all the JNIEnv operations), and then releases the lock. This
approach was tried but was so disruptive refactor-wise that I deemed it too dangerous to try and push through. So
instead, we just have to be careful with acquire/release.
In this way, the vast majority of usage is relatively contentionless; it's just a bunch of native threads taking
read locks on a shared rw lock. Only when the JVM shutdown hook calls into native is there read-write contention.
*/
static struct aws_rw_lock s_jvm_table_lock = AWS_RW_LOCK_INIT;
static struct aws_hash_table *s_jvms = NULL;
static void s_jvm_table_add_jvm_for_env(JNIEnv *env) {
aws_rw_lock_wlock(&s_jvm_table_lock);
if (s_jvms == NULL) {
/* use default allocator so that tracing allocator doesn't flag this as a leak during tests */
s_jvms = aws_mem_calloc(aws_default_allocator(), 1, sizeof(struct aws_hash_table));
AWS_FATAL_ASSERT(
AWS_OP_SUCCESS ==
aws_hash_table_init(s_jvms, aws_default_allocator(), 1, aws_hash_ptr, aws_ptr_eq, NULL, NULL));
}
JavaVM *jvm = NULL;
jint jvmresult = (*env)->GetJavaVM(env, &jvm);
AWS_FATAL_ASSERT(jvmresult == 0 && jvm != NULL);
int was_created = 0;
AWS_FATAL_ASSERT(AWS_OP_SUCCESS == aws_hash_table_put(s_jvms, jvm, NULL, &was_created));
AWS_FATAL_ASSERT(was_created == 1);
aws_rw_lock_wunlock(&s_jvm_table_lock);
}
static void s_jvm_table_remove_jvm_for_env(JNIEnv *env) {
aws_rw_lock_wlock(&s_jvm_table_lock);
if (s_jvms == NULL) {
goto done;
}
JavaVM *jvm = NULL;
jint jvmresult = (*env)->GetJavaVM(env, &jvm);
AWS_FATAL_ASSERT(jvmresult == 0 && jvm != NULL);
AWS_FATAL_ASSERT(AWS_OP_SUCCESS == aws_hash_table_remove(s_jvms, jvm, NULL, NULL));
if (aws_hash_table_get_entry_count(s_jvms) == 0) {
aws_hash_table_clean_up(s_jvms);
aws_mem_release(aws_default_allocator(), s_jvms);
s_jvms = NULL;
}
done:
aws_rw_lock_wunlock(&s_jvm_table_lock);
}
struct aws_jvm_env_context aws_jni_acquire_thread_env(JavaVM *jvm) {
struct aws_jvm_env_context jvm_env_context = {
.env = NULL,
.should_detach = false,
};
/*
* We use try-lock here in order to avoid the re-entrant deadlock case that could happen if we have a read
* lock already, the JVM shutdown hooks causes another thread to block on taking the write lock, and then
* we try to reacquire the read-lock recursively due to some synchronous code path. That case can deadlock
* but since the JVM is going away, it's safe to just fail completely from here on out.
*/
if (aws_rw_lock_try_rlock(&s_jvm_table_lock)) {
if (aws_last_error() != AWS_ERROR_UNSUPPORTED_OPERATION) {
aws_raise_error(AWS_ERROR_JAVA_CRT_JVM_DESTROYED);
}
return jvm_env_context;
}
if (s_jvms == NULL) {
aws_raise_error(AWS_ERROR_JAVA_CRT_JVM_DESTROYED);
goto error;
}
struct aws_hash_element *element = NULL;
int find_result = aws_hash_table_find(s_jvms, jvm, &element);
if (find_result != AWS_OP_SUCCESS || element == NULL) {
aws_raise_error(AWS_ERROR_JAVA_CRT_JVM_DESTROYED);
goto error;
}
jvm_env_context = s_aws_jni_get_thread_env(jvm);
if (jvm_env_context.env == NULL) {
aws_raise_error(AWS_ERROR_JAVA_CRT_JVM_DESTROYED);
goto error;
}
return jvm_env_context;
error:
aws_rw_lock_runlock(&s_jvm_table_lock);
return jvm_env_context;
}
void aws_jni_release_thread_env(JavaVM *jvm, struct aws_jvm_env_context *jvm_env_context) {
if (jvm_env_context->env != NULL) {
/*
Dispatch Queue threads must be manually detached after they're used instead of depending
on a thread exit callback due to the threads not being managed by the CRT and thus, their
lifetimes not trackable outside the context of their immediate use.
An additional needs_detach variable is needed to avoid detaching JVM threads. It happens
when a callback is executed on a JVM thread.
*/
if (s_dispatch_queue_threads && jvm_env_context->should_detach) {
(*jvm)->DetachCurrentThread(jvm);
}
aws_rw_lock_runlock(&s_jvm_table_lock);
}
}
void aws_jni_throw_runtime_exception(JNIEnv *env, const char *msg, ...) {
va_list args;
va_start(args, msg);
char buf[1024];
vsnprintf(buf, sizeof(buf), msg, args);
va_end(args);
int error = aws_last_error();
char exception[1280];
snprintf(
exception,
sizeof(exception),
"%s (aws_last_error: %s(%d), %s)",
buf,
aws_error_name(error),
error,
aws_error_str(error));
jclass runtime_exception = crt_runtime_exception_properties.crt_runtime_exception_class;
(*env)->ThrowNew(env, runtime_exception, exception);
}
void aws_jni_throw_null_pointer_exception(JNIEnv *env, const char *msg, ...) {
va_list args;
va_start(args, msg);
char buf[1024];
vsnprintf(buf, sizeof(buf), msg, args);
va_end(args);
(*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/NullPointerException"), buf);
}
void aws_jni_throw_out_of_memory_exception(JNIEnv *env, const char *msg, ...) {
va_list args;
va_start(args, msg);
char buf[1024];
vsnprintf(buf, sizeof(buf), msg, args);
va_end(args);
(*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/OutOfMemoryError"), buf);
}
void aws_jni_throw_illegal_argument_exception(JNIEnv *env, const char *msg, ...) {
va_list args;
va_start(args, msg);
char buf[1024];
vsnprintf(buf, sizeof(buf), msg, args);
va_end(args);
(*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/IllegalArgumentException"), buf);
}
bool aws_jni_check_and_clear_exception(JNIEnv *env) {
bool exception_pending = (*env)->ExceptionCheck(env);
if (exception_pending) {
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
return exception_pending;
}
bool aws_jni_get_and_clear_exception(JNIEnv *env, jthrowable *out) {
bool exception_pending = (*env)->ExceptionCheck(env);
if (exception_pending) {
(*env)->DeleteGlobalRef(env, *out);
*out = (jthrowable)(*env)->NewGlobalRef(env, (*env)->ExceptionOccurred(env));
(*env)->ExceptionClear(env);
}
return exception_pending;
}
int aws_size_t_from_java(JNIEnv *env, size_t *out_size, jlong java_long, const char *errmsg_prefix) {
if (java_long < 0) {
aws_jni_throw_illegal_argument_exception(env, "%s cannot be negative", errmsg_prefix);
goto error;
}
if ((uint64_t)java_long > (uint64_t)SIZE_MAX) {
aws_jni_throw_illegal_argument_exception(
env, "%s cannot exceed %zu when running 32bit", errmsg_prefix, SIZE_MAX);
goto error;
}
*out_size = (size_t)java_long;
return AWS_OP_SUCCESS;
error:
*out_size = 0;
return AWS_OP_ERR;
}
int aws_uint64_t_from_java_Long(JNIEnv *env, uint64_t *out_long, jobject java_Long, const char *errmsg_prefix) {
if (java_Long == NULL) {
aws_jni_throw_null_pointer_exception(env, "%s can't be null");
goto error;
}
jlong jlong_value = (*env)->CallLongMethod(env, java_Long, boxed_long_properties.long_value_method_id);
if ((*env)->ExceptionCheck(env)) {
goto error;
}
int64_t jlong_value_int64 = (int64_t)jlong_value;
if (jlong_value_int64 < 0) {
aws_jni_throw_illegal_argument_exception(env, "%s cannot be negative", errmsg_prefix);
goto error;
}
*out_long = (uint64_t)jlong_value_int64;
return AWS_OP_SUCCESS;
error:
*out_long = 0;
return AWS_OP_ERR;
}
jbyteArray aws_java_byte_array_new(JNIEnv *env, size_t size) {
jbyteArray jArray = (*env)->NewByteArray(env, (jsize)size);
return jArray;
}
bool aws_copy_native_array_to_java_byte_array(JNIEnv *env, jbyteArray dst, uint8_t *src, size_t amount) {
(*env)->SetByteArrayRegion(env, dst, 0, (jsize)amount, (jbyte *)src);
return aws_jni_check_and_clear_exception(env);
}
/**
* Converts a Native aws_byte_cursor to a Java byte[]
*/
jbyteArray aws_jni_byte_array_from_cursor(JNIEnv *env, const struct aws_byte_cursor *native_data) {
jbyteArray jArray = aws_java_byte_array_new(env, native_data->len);
if (jArray) {
if (!aws_copy_native_array_to_java_byte_array(env, jArray, native_data->ptr, native_data->len)) {
return jArray;
}
}
return NULL;
}
/**
* Get the Buffer Position (the next element to read/write)
*/
int aws_jni_byte_buffer_get_position(JNIEnv *env, jobject java_byte_buffer) {
jint position = (*env)->CallIntMethod(env, java_byte_buffer, byte_buffer_properties.get_position);
return (aws_jni_check_and_clear_exception(env)) ? -1 : (int)position;
}
/**
* Set the Buffer Position (the next element to read/write)
*/
void aws_jni_byte_buffer_set_position(JNIEnv *env, jobject jByteBuf, jint position) {
jobject val = (*env)->CallObjectMethod(env, jByteBuf, byte_buffer_properties.set_position, position);
AWS_FATAL_ASSERT(!aws_jni_check_and_clear_exception(env));
(*env)->DeleteLocalRef(env, val);
}
/**
* Set the Buffer Limit (the max allowed element to read/write)
*/
void aws_jni_byte_buffer_set_limit(JNIEnv *env, jobject jByteBuf, jint limit) {
jobject val = (*env)->CallObjectMethod(env, jByteBuf, byte_buffer_properties.set_limit, limit);
AWS_FATAL_ASSERT(!aws_jni_check_and_clear_exception(env));
(*env)->DeleteLocalRef(env, val);
}
jobject aws_jni_direct_byte_buffer_from_raw_ptr(JNIEnv *env, const void *dst, size_t capacity) {
jobject jByteBuf = (*env)->NewDirectByteBuffer(env, (void *)dst, (jlong)capacity);
if (jByteBuf) {
aws_jni_byte_buffer_set_limit(env, jByteBuf, (jint)capacity);
aws_jni_byte_buffer_set_position(env, jByteBuf, 0);
} else {
if (aws_jni_check_and_clear_exception(env)) {
(void)aws_raise_error(AWS_ERROR_HTTP_CALLBACK_FAILURE);
}
}
return jByteBuf;
}
struct aws_byte_cursor aws_jni_byte_cursor_from_jstring_acquire(JNIEnv *env, jstring str) {
if (str == NULL) {
aws_jni_throw_null_pointer_exception(env, "string is null");
return aws_byte_cursor_from_array(NULL, 0);
}
const char *bytes = (*env)->GetStringUTFChars(env, str, NULL);
if (bytes == NULL) {
/* GetStringUTFChars() has thrown exception */
return aws_byte_cursor_from_array(NULL, 0);
}
return aws_byte_cursor_from_array(bytes, (size_t)(*env)->GetStringUTFLength(env, str));
}
void aws_jni_byte_cursor_from_jstring_release(JNIEnv *env, jstring str, struct aws_byte_cursor cur) {
if (cur.ptr != NULL) {
(*env)->ReleaseStringUTFChars(env, str, (const char *)cur.ptr);
}
}
struct aws_byte_cursor aws_jni_byte_cursor_from_jbyteArray_acquire(JNIEnv *env, jbyteArray array) {
if (array == NULL) {
aws_jni_throw_null_pointer_exception(env, "byte[] is null");
return aws_byte_cursor_from_array(NULL, 0);
}
jbyte *bytes = (*env)->GetByteArrayElements(env, array, NULL);
if (bytes == NULL) {
/* GetByteArrayElements() has thrown exception */
return aws_byte_cursor_from_array(NULL, 0);
}
size_t len = (*env)->GetArrayLength(env, array);
return aws_byte_cursor_from_array(bytes, len);
}
struct aws_byte_cursor aws_jni_byte_cursor_from_jbyteArray_critical_acquire(JNIEnv *env, jbyteArray array) {
if (array == NULL) {
aws_jni_throw_null_pointer_exception(env, "byte[] is null");
return aws_byte_cursor_from_array(NULL, 0);
}
jbyte *bytes = (*env)->GetPrimitiveArrayCritical(env, array, NULL);
if (bytes == NULL) {
aws_jni_throw_out_of_memory_exception(env, "failed to acquire array memory");
return aws_byte_cursor_from_array(NULL, 0);
}
size_t len = (*env)->GetArrayLength(env, array);
return aws_byte_cursor_from_array(bytes, len);
}
void aws_jni_byte_cursor_from_jbyteArray_release(JNIEnv *env, jbyteArray array, struct aws_byte_cursor cur) {
if (cur.ptr != NULL) {
(*env)->ReleaseByteArrayElements(env, array, (jbyte *)cur.ptr, JNI_ABORT);
}
}
void aws_jni_byte_cursor_from_jbyteArray_critical_release(JNIEnv *env, jbyteArray array, struct aws_byte_cursor cur) {
if (cur.ptr != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, array, (jbyte *)cur.ptr, JNI_ABORT);
}
}
struct aws_byte_cursor aws_jni_byte_cursor_from_direct_byte_buffer(JNIEnv *env, jobject byte_buffer) {
jlong payload_size = (*env)->GetDirectBufferCapacity(env, byte_buffer);
if (payload_size == -1) {
aws_jni_throw_runtime_exception(
env, "MqttClientConnection.mqtt_publish: Unable to get capacity of payload ByteBuffer");
return aws_byte_cursor_from_array(NULL, 0);
}
jbyte *payload_data = (*env)->GetDirectBufferAddress(env, byte_buffer);
if (!payload_data) {
aws_jni_throw_runtime_exception(
env, "MqttClientConnection.mqtt_publish: Unable to get buffer from payload ByteBuffer");
return aws_byte_cursor_from_array(NULL, 0);
}
return aws_byte_cursor_from_array((const uint8_t *)payload_data, (size_t)payload_size);
}
struct aws_string *aws_jni_new_string_from_jstring(JNIEnv *env, jstring str) {
struct aws_allocator *allocator = aws_jni_get_allocator();
const char *str_chars = (*env)->GetStringUTFChars(env, str, NULL);
if (!str_chars) {
aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
return NULL;
}
struct aws_string *result = aws_string_new_from_c_str(allocator, str_chars);
(*env)->ReleaseStringUTFChars(env, str, str_chars);
return result;
}
jobject aws_jni_new_crt_exception_from_error_code(JNIEnv *env, int error_code) {
jint jni_error_code = error_code;
jobject crt_exception = (*env)->NewObject(
env,
crt_runtime_exception_properties.crt_runtime_exception_class,
crt_runtime_exception_properties.constructor_method_id,
jni_error_code);
AWS_FATAL_ASSERT(crt_exception);
return crt_exception;
}
#define AWS_DEFINE_ERROR_INFO_CRT(CODE, STR) AWS_DEFINE_ERROR_INFO(CODE, STR, "aws-crt-java")
/* clang-format off */
static struct aws_error_info s_crt_errors[] = {
AWS_DEFINE_ERROR_INFO_CRT(
AWS_ERROR_JAVA_CRT_JVM_DESTROYED,
"Attempt to use a JVM that has already been destroyed"),
AWS_DEFINE_ERROR_INFO_CRT(
AWS_ERROR_JAVA_CRT_JVM_OUT_OF_MEMORY,
"OutOfMemoryError has been raised from JVM."),
};
/* clang-format on */
static struct aws_error_info_list s_crt_error_list = {
.error_list = s_crt_errors,
.count = sizeof(s_crt_errors) / sizeof(struct aws_error_info),
};
static struct aws_log_subject_info s_crt_log_subject_infos[] = {
/* clang-format off */
DEFINE_LOG_SUBJECT_INFO(
AWS_LS_JAVA_CRT_GENERAL, "JavaCrtGeneral", "Subject for aws-crt-java logging that defies categorization"),
DEFINE_LOG_SUBJECT_INFO(
AWS_LS_JAVA_CRT_RESOURCE, "JavaCrtResource", "Subject for CrtResource"),
DEFINE_LOG_SUBJECT_INFO(
AWS_LS_JAVA_CRT_S3, "JavaCrtS3", "Subject for the layer binding aws-c-s3 to Java"),
DEFINE_LOG_SUBJECT_INFO(
AWS_LS_JAVA_ANDROID_KEYCHAIN, "android-keychain", "Subject for Android KeyChain"),
/* clang-format on */
};
static struct aws_log_subject_info_list s_crt_log_subject_list = {
.subject_list = s_crt_log_subject_infos,
.count = AWS_ARRAY_SIZE(s_crt_log_subject_infos),
};
static void s_jni_atexit_strict(void) {
aws_unregister_log_subject_info_list(&s_crt_log_subject_list);
aws_unregister_error_info(&s_crt_error_list);
aws_s3_library_clean_up();
aws_event_stream_library_clean_up();
aws_auth_library_clean_up();
aws_http_library_clean_up();
aws_mqtt_library_clean_up();
if (g_memory_tracing) {
struct aws_allocator *tracer_allocator = aws_jni_get_allocator();
aws_mem_tracer_dump(tracer_allocator);
}
aws_jni_cleanup_logging();
if (g_memory_tracing) {
struct aws_allocator *tracer_allocator = aws_jni_get_allocator();
aws_mem_tracer_destroy(tracer_allocator);
}
s_allocator = NULL;
}
#define DEFAULT_MANAGED_SHUTDOWN_WAIT_IN_SECONDS 1
static void s_jni_atexit_gentle(void) {
/* If not doing strict shutdown, wait only a short time before shutting down */
aws_thread_set_managed_join_timeout_ns(
aws_timestamp_convert(DEFAULT_MANAGED_SHUTDOWN_WAIT_IN_SECONDS, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL));
if (aws_thread_join_all_managed() == AWS_OP_SUCCESS) {
/* a successful managed join means it should be safe to do a full, strict clean up */
s_jni_atexit_strict();
} else {
/*
* We didn't successfully join all our threads so it's not really safe to clean up the libraries.
* Just dump memory if applicable and exit.
*/
AWS_LOGF_WARN(
AWS_LS_JAVA_CRT_GENERAL,
"Not all native threads were successfully joined during gentle shutdown. Memory may be leaked.");
if (g_memory_tracing) {
AWS_LOGF_DEBUG(
AWS_LS_JAVA_CRT_GENERAL,
"At shutdown, %u bytes remaining",
(uint32_t)aws_mem_tracer_bytes(aws_jni_get_allocator()));
if (g_memory_tracing > 1) {
aws_mem_tracer_dump(aws_jni_get_allocator());
}
}
}
}
#define KB_256 (256 * 1024)
/* Called as the entry point, immediately after the shared lib is loaded the first time by JNI */
JNIEXPORT
void JNICALL Java_software_amazon_awssdk_crt_CRT_awsCrtInit(
JNIEnv *env,
jclass jni_crt_class,
jint jni_memtrace,
jboolean jni_debug_wait,
jboolean jni_strict_shutdown) {
(void)jni_crt_class;
if (jni_debug_wait) {
bool done = false;
while (!done) {
;
}
}
g_memory_tracing = jni_memtrace;
/*
* Increase the maximum channel message size in order to improve throughput on large payloads.
* Consider adding a system property override in the future.
*/
g_aws_channel_max_fragment_size = KB_256;
/* check to see if we have support for backtraces only if we need to */
void *stack[1];
if (g_memory_tracing > 1 && 0 == aws_backtrace(stack, 1)) {
g_memory_tracing = 1;
}
/* FIPS mode can be checked if OpenSSL was configured and built for FIPS which then defines OPENSSL_FIPS.
*
* AWS-LC always defines FIPS_mode() that you can call and check what the library was built with. It does not define
* a public OPENSSL_FIPS/AWSLC_FIPS macro that we can (or need to) check here
*
* Safeguard with macro's, for example because Libressl doesn't define
* FIPS_mode() by default.
* */
#if defined(OPENSSL_FIPS) || defined(OPENSSL_IS_AWSLC)
/* Try to enable fips mode for libcrypto */
g_crt_fips_mode = FIPS_mode_set(1);
#endif
/* NOT using aws_jni_get_allocator to avoid trace leak outside the test */
struct aws_allocator *allocator = aws_default_allocator();
aws_mqtt_library_init(allocator);
aws_http_library_init(allocator);
aws_auth_library_init(allocator);
aws_event_stream_library_init(allocator);
aws_s3_library_init(allocator);
aws_register_error_info(&s_crt_error_list);
aws_register_log_subject_info_list(&s_crt_log_subject_list);
s_jvm_table_add_jvm_for_env(env);
if (jni_strict_shutdown) {
atexit(s_jni_atexit_strict);
} else {
atexit(s_jni_atexit_gentle);
}
}
JNIEXPORT
jboolean JNICALL
Java_software_amazon_awssdk_crt_CRT_awsIsTransientError(JNIEnv *env, jclass jni_crt_class, jint error_code) {
(void)env;
(void)jni_crt_class;
return aws_http_error_code_is_retryable(error_code);
}
JNIEXPORT
void JNICALL Java_software_amazon_awssdk_crt_CRT_onJvmShutdown(JNIEnv *env, jclass jni_crt_class) {
(void)jni_crt_class;
s_jvm_table_remove_jvm_for_env(env);
}
JNIEXPORT
jint JNICALL Java_software_amazon_awssdk_crt_CRT_awsLastError(JNIEnv *env, jclass jni_crt_class) {
(void)env;
(void)jni_crt_class;
return aws_last_error();
}
JNIEXPORT
jstring JNICALL Java_software_amazon_awssdk_crt_CRT_awsErrorString(JNIEnv *env, jclass jni_crt_class, jint error_code) {
(void)jni_crt_class;
const char *error_msg = aws_error_str(error_code);
return (*env)->NewStringUTF(env, error_msg);
}
JNIEXPORT
jstring JNICALL Java_software_amazon_awssdk_crt_CRT_awsErrorName(JNIEnv *env, jclass jni_crt_class, jint error_code) {
(void)jni_crt_class;
const char *error_msg = aws_error_name(error_code);
return (*env)->NewStringUTF(env, error_msg);
}
JNIEXPORT
jlong JNICALL Java_software_amazon_awssdk_crt_CRT_awsNativeMemory(JNIEnv *env, jclass jni_crt_class) {
(void)env;
(void)jni_crt_class;
jlong allocated = 0;
if (g_memory_tracing) {
allocated = (jlong)aws_mem_tracer_bytes(aws_jni_get_allocator());
}
return allocated;
}
JNIEXPORT
void JNICALL Java_software_amazon_awssdk_crt_CRT_dumpNativeMemory(JNIEnv *env, jclass jni_crt_class) {
(void)env;
(void)jni_crt_class;
if (g_memory_tracing > 1) {
aws_mem_tracer_dump(aws_jni_get_allocator());
}
}
JNIEXPORT
jboolean JNICALL Java_software_amazon_awssdk_crt_CRT_isFIPS(JNIEnv *env, jclass jni_crt_class) {
(void)env;
(void)jni_crt_class;
return g_crt_fips_mode == 1;
}
jstring aws_jni_string_from_cursor(JNIEnv *env, const struct aws_byte_cursor *native_data) {
struct aws_string *string = aws_string_new_from_array(aws_jni_get_allocator(), native_data->ptr, native_data->len);
AWS_FATAL_ASSERT(string != NULL);
jstring java_string = (*env)->NewStringUTF(env, aws_string_c_str(string));
aws_string_destroy(string);
return java_string;
}
jstring aws_jni_string_from_string(JNIEnv *env, const struct aws_string *string) {
AWS_FATAL_ASSERT(string != NULL);
jstring java_string = (*env)->NewStringUTF(env, aws_string_c_str(string));
return java_string;
}
JNIEXPORT
void JNICALL Java_software_amazon_awssdk_crt_CrtResource_waitForGlobalResourceDestruction(
JNIEnv *env,
jclass jni_crt_resource_class,
jint timeout_in_seconds) {
(void)env;
(void)jni_crt_resource_class;
aws_thread_set_managed_join_timeout_ns(
aws_timestamp_convert(timeout_in_seconds, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL));
aws_thread_join_all_managed();
if (g_memory_tracing) {
AWS_LOGF_DEBUG(
AWS_LS_COMMON_GENERAL,
"At shutdown, %u bytes remaining",
(uint32_t)aws_mem_tracer_bytes(aws_jni_get_allocator()));
if (g_memory_tracing > 1) {
aws_mem_tracer_dump(aws_jni_get_allocator());
}
}
}
JNIEXPORT
void JNICALL Java_software_amazon_awssdk_crt_CRT_nativeCheckJniExceptionContract(
JNIEnv *env,
jclass jni_crt_class,
jboolean clear_exception) {
(*env)->CallStaticVoidMethod(env, jni_crt_class, crt_properties.test_jni_exception_method_id, true);
if (clear_exception) {
(*env)->ExceptionClear(env);
(*env)->CallStaticVoidMethod(env, jni_crt_class, crt_properties.test_jni_exception_method_id, false);
} else {
(*env)->ExceptionCheck(env);
}
}