1 /*
2  * Copyright (c) 2017 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 
8 #include <zephyr/kernel.h>
9 #include <string.h>
10 #include <zephyr/sys/math_extras.h>
11 #include <zephyr/sys/rb.h>
12 #include <zephyr/kernel_structs.h>
13 #include <zephyr/sys/sys_io.h>
14 #include <ksched.h>
15 #include <zephyr/syscall.h>
16 #include <zephyr/internal/syscall_handler.h>
17 #include <zephyr/device.h>
18 #include <zephyr/init.h>
19 #include <stdbool.h>
20 #include <zephyr/app_memory/app_memdomain.h>
21 #include <zephyr/sys/libc-hooks.h>
22 #include <zephyr/sys/mutex.h>
23 #include <zephyr/sys/util.h>
24 #include <inttypes.h>
25 #include <zephyr/linker/linker-defs.h>
26 
27 #ifdef Z_LIBC_PARTITION_EXISTS
28 K_APPMEM_PARTITION_DEFINE(z_libc_partition);
29 #endif /* Z_LIBC_PARTITION_EXISTS */
30 
31 /* TODO: Find a better place to put this. Since we pull the entire
32  * lib..__modules__crypto__mbedtls.a  globals into app shared memory
33  * section, we can't put this in zephyr_init.c of the mbedtls module.
34  */
35 #ifdef CONFIG_MBEDTLS
36 K_APPMEM_PARTITION_DEFINE(k_mbedtls_partition);
37 #endif /* CONFIG_MBEDTLS */
38 
39 #include <zephyr/logging/log.h>
40 LOG_MODULE_DECLARE(os, CONFIG_KERNEL_LOG_LEVEL);
41 
42 /* The originally synchronization strategy made heavy use of recursive
43  * irq_locking, which ports poorly to spinlocks which are
44  * non-recursive.  Rather than try to redesign as part of
45  * spinlockification, this uses multiple locks to preserve the
46  * original semantics exactly.  The locks are named for the data they
47  * protect where possible, or just for the code that uses them where
48  * not.
49  */
50 #ifdef CONFIG_DYNAMIC_OBJECTS
51 static struct k_spinlock lists_lock;       /* kobj dlist */
52 static struct k_spinlock objfree_lock;     /* k_object_free */
53 
54 #ifdef CONFIG_GEN_PRIV_STACKS
55 /* On ARM & ARC MPU & RISC-V PMP we may have two different alignment requirement
56  * when dynamically allocating thread stacks, one for the privileged
57  * stack and other for the user stack, so we need to account the
58  * worst alignment scenario and reserve space for that.
59  */
60 #if defined(CONFIG_ARM_MPU) || defined(CONFIG_ARC_MPU) || defined(CONFIG_RISCV_PMP)
61 #define STACK_ELEMENT_DATA_SIZE(size) \
62 	(sizeof(struct z_stack_data) + CONFIG_PRIVILEGED_STACK_SIZE + \
63 	Z_THREAD_STACK_OBJ_ALIGN(size) + K_THREAD_STACK_LEN(size))
64 #else
65 #define STACK_ELEMENT_DATA_SIZE(size) (sizeof(struct z_stack_data) + \
66 	K_THREAD_STACK_LEN(size))
67 #endif /* CONFIG_ARM_MPU || CONFIG_ARC_MPU || CONFIG_RISCV_PMP */
68 #else
69 #define STACK_ELEMENT_DATA_SIZE(size) K_THREAD_STACK_LEN(size)
70 #endif /* CONFIG_GEN_PRIV_STACKS */
71 
72 #endif /* CONFIG_DYNAMIC_OBJECTS */
73 static struct k_spinlock obj_lock;         /* kobj struct data */
74 
75 #define MAX_THREAD_BITS (CONFIG_MAX_THREAD_BYTES * BITS_PER_BYTE)
76 
77 #ifdef CONFIG_DYNAMIC_OBJECTS
78 extern uint8_t _thread_idx_map[CONFIG_MAX_THREAD_BYTES];
79 #endif /* CONFIG_DYNAMIC_OBJECTS */
80 
81 static void clear_perms_cb(struct k_object *ko, void *ctx_ptr);
82 
otype_to_str(enum k_objects otype)83 const char *otype_to_str(enum k_objects otype)
84 {
85 	const char *ret;
86 	/* -fdata-sections doesn't work right except in very recent
87 	 * GCC and these literal strings would appear in the binary even if
88 	 * otype_to_str was omitted by the linker
89 	 */
90 #ifdef CONFIG_LOG
91 	switch (otype) {
92 	/* otype-to-str.h is generated automatically during build by
93 	 * gen_kobject_list.py
94 	 */
95 	case K_OBJ_ANY:
96 		ret = "generic";
97 		break;
98 #include <zephyr/otype-to-str.h>
99 	default:
100 		ret = "?";
101 		break;
102 	}
103 #else
104 	ARG_UNUSED(otype);
105 	ret = NULL;
106 #endif /* CONFIG_LOG */
107 	return ret;
108 }
109 
110 struct perm_ctx {
111 	int parent_id;
112 	int child_id;
113 	struct k_thread *parent;
114 };
115 
116 #ifdef CONFIG_GEN_PRIV_STACKS
117 /* See write_gperf_table() in scripts/build/gen_kobject_list.py. The privilege
118  * mode stacks are allocated as an array. The base of the array is
119  * aligned to Z_PRIVILEGE_STACK_ALIGN, and all members must be as well.
120  */
z_priv_stack_find(k_thread_stack_t * stack)121 uint8_t *z_priv_stack_find(k_thread_stack_t *stack)
122 {
123 	struct k_object *obj = k_object_find(stack);
124 
125 	__ASSERT(obj != NULL, "stack object not found");
126 	__ASSERT(obj->type == K_OBJ_THREAD_STACK_ELEMENT,
127 		 "bad stack object");
128 
129 	return obj->data.stack_data->priv;
130 }
131 #endif /* CONFIG_GEN_PRIV_STACKS */
132 
133 #ifdef CONFIG_DYNAMIC_OBJECTS
134 
135 /*
136  * Note that dyn_obj->data is where the kernel object resides
137  * so it is the one that actually needs to be aligned.
138  * Due to the need to get the fields inside struct dyn_obj
139  * from kernel object pointers (i.e. from data[]), the offset
140  * from data[] needs to be fixed at build time. Therefore,
141  * data[] is declared with __aligned(), such that when dyn_obj
142  * is allocated with alignment, data[] is also aligned.
143  * Due to this requirement, data[] needs to be aligned with
144  * the maximum alignment needed for all kernel objects
145  * (hence the following DYN_OBJ_DATA_ALIGN).
146  */
147 #ifdef ARCH_DYNAMIC_OBJ_K_THREAD_ALIGNMENT
148 #define DYN_OBJ_DATA_ALIGN_K_THREAD	(ARCH_DYNAMIC_OBJ_K_THREAD_ALIGNMENT)
149 #else
150 #define DYN_OBJ_DATA_ALIGN_K_THREAD	(sizeof(void *))
151 #endif /* ARCH_DYNAMIC_OBJ_K_THREAD_ALIGNMENT */
152 
153 #ifdef CONFIG_DYNAMIC_THREAD_STACK_SIZE
154 #if defined(CONFIG_MPU_STACK_GUARD) || defined(CONFIG_PMP_STACK_GUARD)
155 #define DYN_OBJ_DATA_ALIGN_K_THREAD_STACK \
156 	Z_THREAD_STACK_OBJ_ALIGN(CONFIG_DYNAMIC_THREAD_STACK_SIZE)
157 #else
158 #define DYN_OBJ_DATA_ALIGN_K_THREAD_STACK \
159 	Z_THREAD_STACK_OBJ_ALIGN(CONFIG_PRIVILEGED_STACK_SIZE)
160 #endif /* CONFIG_MPU_STACK_GUARD || CONFIG_PMP_STACK_GUARD */
161 #else
162 #define DYN_OBJ_DATA_ALIGN_K_THREAD_STACK \
163 	Z_THREAD_STACK_OBJ_ALIGN(ARCH_STACK_PTR_ALIGN)
164 #endif /* CONFIG_DYNAMIC_THREAD_STACK_SIZE */
165 
166 #define DYN_OBJ_DATA_ALIGN		\
167 	MAX(DYN_OBJ_DATA_ALIGN_K_THREAD, (sizeof(void *)))
168 
169 struct dyn_obj {
170 	struct k_object kobj;
171 	sys_dnode_t dobj_list;
172 
173 	/* The object itself */
174 	void *data;
175 };
176 
177 extern struct k_object *z_object_gperf_find(const void *obj);
178 extern void z_object_gperf_wordlist_foreach(_wordlist_cb_func_t func,
179 					     void *context);
180 
181 /*
182  * Linked list of allocated kernel objects, for iteration over all allocated
183  * objects (and potentially deleting them during iteration).
184  */
185 static sys_dlist_t obj_list = SYS_DLIST_STATIC_INIT(&obj_list);
186 
187 /*
188  * TODO: Write some hash table code that will replace obj_list.
189  */
190 
obj_size_get(enum k_objects otype)191 static size_t obj_size_get(enum k_objects otype)
192 {
193 	size_t ret;
194 
195 	switch (otype) {
196 #include <zephyr/otype-to-size.h>
197 	default:
198 		ret = sizeof(const struct device);
199 		break;
200 	}
201 
202 	return ret;
203 }
204 
obj_align_get(enum k_objects otype)205 static size_t obj_align_get(enum k_objects otype)
206 {
207 	size_t ret;
208 
209 	switch (otype) {
210 	case K_OBJ_THREAD:
211 #ifdef ARCH_DYNAMIC_OBJ_K_THREAD_ALIGNMENT
212 		ret = ARCH_DYNAMIC_OBJ_K_THREAD_ALIGNMENT;
213 #else
214 		ret = __alignof(struct dyn_obj);
215 #endif /* ARCH_DYNAMIC_OBJ_K_THREAD_ALIGNMENT */
216 		break;
217 	default:
218 		ret = __alignof(struct dyn_obj);
219 		break;
220 	}
221 
222 	return ret;
223 }
224 
dyn_object_find(const void * obj)225 static struct dyn_obj *dyn_object_find(const void *obj)
226 {
227 	struct dyn_obj *node;
228 	k_spinlock_key_t key;
229 
230 	/* For any dynamically allocated kernel object, the object
231 	 * pointer is just a member of the containing struct dyn_obj,
232 	 * so just a little arithmetic is necessary to locate the
233 	 * corresponding struct rbnode
234 	 */
235 	key = k_spin_lock(&lists_lock);
236 
237 	SYS_DLIST_FOR_EACH_CONTAINER(&obj_list, node, dobj_list) {
238 		if (node->kobj.name == obj) {
239 			goto end;
240 		}
241 	}
242 
243 	/* No object found */
244 	node = NULL;
245 
246  end:
247 	k_spin_unlock(&lists_lock, key);
248 
249 	return node;
250 }
251 
252 /**
253  * @internal
254  *
255  * @brief Allocate a new thread index for a new thread.
256  *
257  * This finds an unused thread index that can be assigned to a new
258  * thread. If too many threads have been allocated, the kernel will
259  * run out of indexes and this function will fail.
260  *
261  * Note that if an unused index is found, that index will be marked as
262  * used after return of this function.
263  *
264  * @param tidx The new thread index if successful
265  *
266  * @return true if successful, false if failed
267  **/
thread_idx_alloc(uintptr_t * tidx)268 static bool thread_idx_alloc(uintptr_t *tidx)
269 {
270 	int i;
271 	int idx;
272 	int base;
273 
274 	base = 0;
275 	for (i = 0; i < CONFIG_MAX_THREAD_BYTES; i++) {
276 		idx = find_lsb_set(_thread_idx_map[i]);
277 
278 		if (idx != 0) {
279 			*tidx = base + (idx - 1);
280 
281 			/* Clear the bit. We already know the array index,
282 			 * and the bit to be cleared.
283 			 */
284 			_thread_idx_map[i] &= ~(BIT(idx - 1));
285 
286 			/* Clear permission from all objects */
287 			k_object_wordlist_foreach(clear_perms_cb,
288 						   (void *)*tidx);
289 
290 			return true;
291 		}
292 
293 		base += 8;
294 	}
295 
296 	return false;
297 }
298 
299 /**
300  * @internal
301  *
302  * @brief Free a thread index.
303  *
304  * This frees a thread index so it can be used by another
305  * thread.
306  *
307  * @param tidx The thread index to be freed
308  **/
thread_idx_free(uintptr_t tidx)309 static void thread_idx_free(uintptr_t tidx)
310 {
311 	/* To prevent leaked permission when index is recycled */
312 	k_object_wordlist_foreach(clear_perms_cb, (void *)tidx);
313 
314 	/* Figure out which bits to set in _thread_idx_map[] and set it. */
315 	int base = tidx / NUM_BITS(_thread_idx_map[0]);
316 	int offset = tidx % NUM_BITS(_thread_idx_map[0]);
317 
318 	_thread_idx_map[base] |= BIT(offset);
319 }
320 
dynamic_object_create(enum k_objects otype,size_t align,size_t size)321 static struct k_object *dynamic_object_create(enum k_objects otype, size_t align,
322 					      size_t size)
323 {
324 	struct dyn_obj *dyn;
325 
326 	dyn = z_thread_aligned_alloc(align, sizeof(struct dyn_obj));
327 	if (dyn == NULL) {
328 		return NULL;
329 	}
330 
331 	if (otype == K_OBJ_THREAD_STACK_ELEMENT) {
332 		size_t adjusted_size;
333 
334 		if (size == 0) {
335 			k_free(dyn);
336 			return NULL;
337 		}
338 
339 		adjusted_size = STACK_ELEMENT_DATA_SIZE(size);
340 		dyn->data = z_thread_aligned_alloc(DYN_OBJ_DATA_ALIGN_K_THREAD_STACK,
341 						     adjusted_size);
342 		if (dyn->data == NULL) {
343 			k_free(dyn);
344 			return NULL;
345 		}
346 
347 #ifdef CONFIG_GEN_PRIV_STACKS
348 		struct z_stack_data *stack_data = (struct z_stack_data *)
349 			((uint8_t *)dyn->data + adjusted_size - sizeof(*stack_data));
350 #if defined(CONFIG_ARM_MPU) || defined(CONFIG_ARC_MPU) || defined(CONFIG_RISCV_PMP)
351 		stack_data->priv = (void *)ROUND_UP(((uint8_t *)dyn->data + size),
352 			  Z_THREAD_STACK_OBJ_ALIGN(size));
353 #else
354 		stack_data->priv = (uint8_t *)dyn->data;
355 #endif /* CONFIG_ARM_MPU || CONFIG_ARC_MPU || CONFIG_RISCV_PMP */
356 		stack_data->size = adjusted_size;
357 		dyn->kobj.data.stack_data = stack_data;
358 		dyn->kobj.name = dyn->data;
359 #else
360 		dyn->kobj.name = dyn->data;
361 		dyn->kobj.data.stack_size = adjusted_size;
362 #endif /* CONFIG_GEN_PRIV_STACKS */
363 	} else {
364 		dyn->data = z_thread_aligned_alloc(align, obj_size_get(otype) + size);
365 		if (dyn->data == NULL) {
366 			k_free(dyn);
367 			return NULL;
368 		}
369 		dyn->kobj.name = dyn->data;
370 	}
371 
372 	dyn->kobj.type = otype;
373 	dyn->kobj.flags = 0;
374 	(void)memset(dyn->kobj.perms, 0, CONFIG_MAX_THREAD_BYTES);
375 
376 	k_spinlock_key_t key = k_spin_lock(&lists_lock);
377 
378 	sys_dlist_append(&obj_list, &dyn->dobj_list);
379 	k_spin_unlock(&lists_lock, key);
380 
381 	return &dyn->kobj;
382 }
383 
k_object_create_dynamic_aligned(size_t align,size_t size)384 struct k_object *k_object_create_dynamic_aligned(size_t align, size_t size)
385 {
386 	struct k_object *obj = dynamic_object_create(K_OBJ_ANY, align, size);
387 
388 	if (obj == NULL) {
389 		LOG_ERR("could not allocate kernel object, out of memory");
390 	}
391 
392 	return obj;
393 }
394 
z_object_alloc(enum k_objects otype,size_t size)395 static void *z_object_alloc(enum k_objects otype, size_t size)
396 {
397 	struct k_object *zo;
398 	uintptr_t tidx = 0;
399 
400 	if ((otype <= K_OBJ_ANY) || (otype >= K_OBJ_LAST)) {
401 		LOG_ERR("bad object type %d requested", otype);
402 		return NULL;
403 	}
404 
405 	switch (otype) {
406 	case K_OBJ_THREAD:
407 		if (!thread_idx_alloc(&tidx)) {
408 			LOG_ERR("out of free thread indexes");
409 			return NULL;
410 		}
411 		break;
412 	/* The following are currently not allowed at all */
413 	case K_OBJ_FUTEX:			/* Lives in user memory */
414 	case K_OBJ_SYS_MUTEX:			/* Lives in user memory */
415 	case K_OBJ_NET_SOCKET:			/* Indeterminate size */
416 		LOG_ERR("forbidden object type '%s' requested",
417 			otype_to_str(otype));
418 		return NULL;
419 	default:
420 		/* Remainder within bounds are permitted */
421 		break;
422 	}
423 
424 	zo = dynamic_object_create(otype, obj_align_get(otype), size);
425 	if (zo == NULL) {
426 		if (otype == K_OBJ_THREAD) {
427 			thread_idx_free(tidx);
428 		}
429 		return NULL;
430 	}
431 
432 	if (otype == K_OBJ_THREAD) {
433 		zo->data.thread_id = tidx;
434 	}
435 
436 	/* The allocating thread implicitly gets permission on kernel objects
437 	 * that it allocates
438 	 */
439 	k_thread_perms_set(zo, _current);
440 
441 	/* Activates reference counting logic for automatic disposal when
442 	 * all permissions have been revoked
443 	 */
444 	zo->flags |= K_OBJ_FLAG_ALLOC;
445 
446 	return zo->name;
447 }
448 
z_impl_k_object_alloc(enum k_objects otype)449 void *z_impl_k_object_alloc(enum k_objects otype)
450 {
451 	return z_object_alloc(otype, 0);
452 }
453 
z_impl_k_object_alloc_size(enum k_objects otype,size_t size)454 void *z_impl_k_object_alloc_size(enum k_objects otype, size_t size)
455 {
456 	return z_object_alloc(otype, size);
457 }
458 
k_object_free(void * obj)459 void k_object_free(void *obj)
460 {
461 	struct dyn_obj *dyn;
462 
463 	/* This function is intentionally not exposed to user mode.
464 	 * There's currently no robust way to track that an object isn't
465 	 * being used by some other thread
466 	 */
467 
468 	k_spinlock_key_t key = k_spin_lock(&objfree_lock);
469 
470 	dyn = dyn_object_find(obj);
471 	if (dyn != NULL) {
472 		sys_dlist_remove(&dyn->dobj_list);
473 
474 		if (dyn->kobj.type == K_OBJ_THREAD) {
475 			thread_idx_free(dyn->kobj.data.thread_id);
476 		}
477 	}
478 	k_spin_unlock(&objfree_lock, key);
479 
480 	if (dyn != NULL) {
481 		k_free(dyn->data);
482 		k_free(dyn);
483 	}
484 }
485 
k_object_find(const void * obj)486 struct k_object *k_object_find(const void *obj)
487 {
488 	struct k_object *ret;
489 
490 	ret = z_object_gperf_find(obj);
491 
492 	if (ret == NULL) {
493 		struct dyn_obj *dyn;
494 
495 		/* The cast to pointer-to-non-const violates MISRA
496 		 * 11.8 but is justified since we know dynamic objects
497 		 * were not declared with a const qualifier.
498 		 */
499 		dyn = dyn_object_find(obj);
500 		if (dyn != NULL) {
501 			ret = &dyn->kobj;
502 		}
503 	}
504 
505 	return ret;
506 }
507 
k_object_wordlist_foreach(_wordlist_cb_func_t func,void * context)508 void k_object_wordlist_foreach(_wordlist_cb_func_t func, void *context)
509 {
510 	struct dyn_obj *obj, *next;
511 
512 	z_object_gperf_wordlist_foreach(func, context);
513 
514 	k_spinlock_key_t key = k_spin_lock(&lists_lock);
515 
516 	SYS_DLIST_FOR_EACH_CONTAINER_SAFE(&obj_list, obj, next, dobj_list) {
517 		func(&obj->kobj, context);
518 	}
519 	k_spin_unlock(&lists_lock, key);
520 }
521 #endif /* CONFIG_DYNAMIC_OBJECTS */
522 
523 /* In the earlier linker-passes before we have the real generated
524  * implementation of the lookup functions, we need some weak dummies.
525  * Being __weak, they will be replaced by the generated implementations in
526  * the later linker passes.
527  */
528 #ifdef CONFIG_DYNAMIC_OBJECTS
529 Z_GENERIC_SECTION(.kobject_data.text.dummies)
z_object_gperf_find(const void * obj)530 __weak struct k_object *z_object_gperf_find(const void *obj)
531 {
532 	return NULL;
533 }
534 Z_GENERIC_SECTION(.kobject_data.text.dummies)
z_object_gperf_wordlist_foreach(_wordlist_cb_func_t func,void * context)535 __weak void z_object_gperf_wordlist_foreach(_wordlist_cb_func_t func, void *context)
536 {
537 }
538 #else
539 Z_GENERIC_SECTION(.kobject_data.text.dummies)
k_object_find(const void * obj)540 __weak struct k_object *k_object_find(const void *obj)
541 {
542 	return NULL;
543 }
544 Z_GENERIC_SECTION(.kobject_data.text.dummies)
k_object_wordlist_foreach(_wordlist_cb_func_t func,void * context)545 __weak void k_object_wordlist_foreach(_wordlist_cb_func_t func, void *context)
546 {
547 }
548 #endif
549 
thread_index_get(struct k_thread * thread)550 static unsigned int thread_index_get(struct k_thread *thread)
551 {
552 	struct k_object *ko;
553 
554 	ko = k_object_find(thread);
555 
556 	if (ko == NULL) {
557 		return -1;
558 	}
559 
560 	return ko->data.thread_id;
561 }
562 
unref_check(struct k_object * ko,uintptr_t index)563 static void unref_check(struct k_object *ko, uintptr_t index)
564 {
565 	k_spinlock_key_t key = k_spin_lock(&obj_lock);
566 
567 	sys_bitfield_clear_bit((mem_addr_t)&ko->perms, index);
568 
569 #ifdef CONFIG_DYNAMIC_OBJECTS
570 	if ((ko->flags & K_OBJ_FLAG_ALLOC) == 0U) {
571 		/* skip unref check for static kernel object */
572 		goto out;
573 	}
574 
575 	void *vko = ko;
576 
577 	struct dyn_obj *dyn = CONTAINER_OF(vko, struct dyn_obj, kobj);
578 
579 	__ASSERT(IS_PTR_ALIGNED(dyn, struct dyn_obj), "unaligned z_object");
580 
581 	for (int i = 0; i < CONFIG_MAX_THREAD_BYTES; i++) {
582 		if (ko->perms[i] != 0U) {
583 			goto out;
584 		}
585 	}
586 
587 	/* This object has no more references. Some objects may have
588 	 * dynamically allocated resources, require cleanup, or need to be
589 	 * marked as uninitialized when all references are gone. What
590 	 * specifically needs to happen depends on the object type.
591 	 */
592 	switch (ko->type) {
593 	case K_OBJ_MSGQ:
594 		k_msgq_cleanup((struct k_msgq *)ko->name);
595 		break;
596 	case K_OBJ_STACK:
597 		k_stack_cleanup((struct k_stack *)ko->name);
598 		break;
599 	default:
600 		/* Nothing to do */
601 		break;
602 	}
603 
604 	sys_dlist_remove(&dyn->dobj_list);
605 	k_free(dyn->data);
606 	k_free(dyn);
607 out:
608 #endif /* CONFIG_DYNAMIC_OBJECTS */
609 	k_spin_unlock(&obj_lock, key);
610 }
611 
wordlist_cb(struct k_object * ko,void * ctx_ptr)612 static void wordlist_cb(struct k_object *ko, void *ctx_ptr)
613 {
614 	struct perm_ctx *ctx = (struct perm_ctx *)ctx_ptr;
615 
616 	if (sys_bitfield_test_bit((mem_addr_t)&ko->perms, ctx->parent_id) &&
617 				  ((struct k_thread *)ko->name != ctx->parent)) {
618 		sys_bitfield_set_bit((mem_addr_t)&ko->perms, ctx->child_id);
619 	}
620 }
621 
k_thread_perms_inherit(struct k_thread * parent,struct k_thread * child)622 void k_thread_perms_inherit(struct k_thread *parent, struct k_thread *child)
623 {
624 	struct perm_ctx ctx = {
625 		thread_index_get(parent),
626 		thread_index_get(child),
627 		parent
628 	};
629 
630 	if ((ctx.parent_id != -1) && (ctx.child_id != -1)) {
631 		k_object_wordlist_foreach(wordlist_cb, &ctx);
632 	}
633 }
634 
k_thread_perms_set(struct k_object * ko,struct k_thread * thread)635 void k_thread_perms_set(struct k_object *ko, struct k_thread *thread)
636 {
637 	int index = thread_index_get(thread);
638 
639 	if (index != -1) {
640 		sys_bitfield_set_bit((mem_addr_t)&ko->perms, index);
641 	}
642 }
643 
k_thread_perms_clear(struct k_object * ko,struct k_thread * thread)644 void k_thread_perms_clear(struct k_object *ko, struct k_thread *thread)
645 {
646 	int index = thread_index_get(thread);
647 
648 	if (index != -1) {
649 		sys_bitfield_clear_bit((mem_addr_t)&ko->perms, index);
650 		unref_check(ko, index);
651 	}
652 }
653 
clear_perms_cb(struct k_object * ko,void * ctx_ptr)654 static void clear_perms_cb(struct k_object *ko, void *ctx_ptr)
655 {
656 	uintptr_t id = (uintptr_t)ctx_ptr;
657 
658 	unref_check(ko, id);
659 }
660 
k_thread_perms_all_clear(struct k_thread * thread)661 void k_thread_perms_all_clear(struct k_thread *thread)
662 {
663 	uintptr_t index = thread_index_get(thread);
664 
665 	if ((int)index != -1) {
666 		k_object_wordlist_foreach(clear_perms_cb, (void *)index);
667 	}
668 }
669 
thread_perms_test(struct k_object * ko)670 static int thread_perms_test(struct k_object *ko)
671 {
672 	int index;
673 
674 	if ((ko->flags & K_OBJ_FLAG_PUBLIC) != 0U) {
675 		return 1;
676 	}
677 
678 	index = thread_index_get(_current);
679 	if (index != -1) {
680 		return sys_bitfield_test_bit((mem_addr_t)&ko->perms, index);
681 	}
682 	return 0;
683 }
684 
dump_permission_error(struct k_object * ko)685 static void dump_permission_error(struct k_object *ko)
686 {
687 	int index = thread_index_get(_current);
688 	LOG_ERR("thread %p (%d) does not have permission on %s %p",
689 		_current, index,
690 		otype_to_str(ko->type), ko->name);
691 	LOG_HEXDUMP_ERR(ko->perms, sizeof(ko->perms), "permission bitmap");
692 }
693 
k_object_dump_error(int retval,const void * obj,struct k_object * ko,enum k_objects otype)694 void k_object_dump_error(int retval, const void *obj, struct k_object *ko,
695 			enum k_objects otype)
696 {
697 	switch (retval) {
698 	case -EBADF:
699 		LOG_ERR("%p is not a valid %s", obj, otype_to_str(otype));
700 		if (ko == NULL) {
701 			LOG_ERR("address is not a known kernel object");
702 		} else {
703 			LOG_ERR("address is actually a %s",
704 				otype_to_str(ko->type));
705 		}
706 		break;
707 	case -EPERM:
708 		dump_permission_error(ko);
709 		break;
710 	case -EINVAL:
711 		LOG_ERR("%p used before initialization", obj);
712 		break;
713 	case -EADDRINUSE:
714 		LOG_ERR("%p %s in use", obj, otype_to_str(otype));
715 		break;
716 	default:
717 		/* Not handled error */
718 		break;
719 	}
720 }
721 
z_impl_k_object_access_grant(const void * object,struct k_thread * thread)722 void z_impl_k_object_access_grant(const void *object, struct k_thread *thread)
723 {
724 	struct k_object *ko = k_object_find(object);
725 
726 	if (ko != NULL) {
727 		k_thread_perms_set(ko, thread);
728 	}
729 }
730 
k_object_access_revoke(const void * object,struct k_thread * thread)731 void k_object_access_revoke(const void *object, struct k_thread *thread)
732 {
733 	struct k_object *ko = k_object_find(object);
734 
735 	if (ko != NULL) {
736 		k_thread_perms_clear(ko, thread);
737 	}
738 }
739 
z_impl_k_object_release(const void * object)740 void z_impl_k_object_release(const void *object)
741 {
742 	k_object_access_revoke(object, _current);
743 }
744 
k_object_access_all_grant(const void * object)745 void k_object_access_all_grant(const void *object)
746 {
747 	struct k_object *ko = k_object_find(object);
748 
749 	if (ko != NULL) {
750 		ko->flags |= K_OBJ_FLAG_PUBLIC;
751 	}
752 }
753 
k_object_validate(struct k_object * ko,enum k_objects otype,enum _obj_init_check init)754 int k_object_validate(struct k_object *ko, enum k_objects otype,
755 		       enum _obj_init_check init)
756 {
757 	if (unlikely((ko == NULL) ||
758 		((otype != K_OBJ_ANY) && (ko->type != otype)))) {
759 		return -EBADF;
760 	}
761 
762 	/* Manipulation of any kernel objects by a user thread requires that
763 	 * thread be granted access first, even for uninitialized objects
764 	 */
765 	if (unlikely(thread_perms_test(ko) == 0)) {
766 		return -EPERM;
767 	}
768 
769 	/* Initialization state checks. _OBJ_INIT_ANY, we don't care */
770 	if (likely(init == _OBJ_INIT_TRUE)) {
771 		/* Object MUST be initialized */
772 		if (unlikely((ko->flags & K_OBJ_FLAG_INITIALIZED) == 0U)) {
773 			return -EINVAL;
774 		}
775 	} else if (init == _OBJ_INIT_FALSE) { /* _OBJ_INIT_FALSE case */
776 		/* Object MUST NOT be initialized */
777 		if (unlikely((ko->flags & K_OBJ_FLAG_INITIALIZED) != 0U)) {
778 			return -EADDRINUSE;
779 		}
780 	} else {
781 		/* _OBJ_INIT_ANY */
782 	}
783 
784 	return 0;
785 }
786 
k_object_init(const void * obj)787 void k_object_init(const void *obj)
788 {
789 	struct k_object *ko;
790 
791 	/* By the time we get here, if the caller was from userspace, all the
792 	 * necessary checks have been done in k_object_validate(), which takes
793 	 * place before the object is initialized.
794 	 *
795 	 * This function runs after the object has been initialized and
796 	 * finalizes it
797 	 */
798 
799 	ko = k_object_find(obj);
800 	if (ko == NULL) {
801 		/* Supervisor threads can ignore rules about kernel objects
802 		 * and may declare them on stacks, etc. Such objects will never
803 		 * be usable from userspace, but we shouldn't explode.
804 		 */
805 		return;
806 	}
807 
808 	/* Allows non-initialization system calls to be made on this object */
809 	ko->flags |= K_OBJ_FLAG_INITIALIZED;
810 }
811 
k_object_recycle(const void * obj)812 void k_object_recycle(const void *obj)
813 {
814 	struct k_object *ko = k_object_find(obj);
815 
816 	if (ko != NULL) {
817 		(void)memset(ko->perms, 0, sizeof(ko->perms));
818 		k_thread_perms_set(ko, _current);
819 		ko->flags |= K_OBJ_FLAG_INITIALIZED;
820 	}
821 }
822 
k_object_uninit(const void * obj)823 void k_object_uninit(const void *obj)
824 {
825 	struct k_object *ko;
826 
827 	/* See comments in k_object_init() */
828 	ko = k_object_find(obj);
829 	if (ko == NULL) {
830 		return;
831 	}
832 
833 	ko->flags &= ~K_OBJ_FLAG_INITIALIZED;
834 }
835 
836 /*
837  * Copy to/from helper functions used in syscall handlers
838  */
k_usermode_alloc_from_copy(const void * src,size_t size)839 void *k_usermode_alloc_from_copy(const void *src, size_t size)
840 {
841 	void *dst = NULL;
842 
843 	/* Does the caller in user mode have access to read this memory? */
844 	if (K_SYSCALL_MEMORY_READ(src, size)) {
845 		goto out_err;
846 	}
847 
848 	dst = z_thread_malloc(size);
849 	if (dst == NULL) {
850 		LOG_ERR("out of thread resource pool memory (%zu)", size);
851 		goto out_err;
852 	}
853 
854 	(void)memcpy(dst, src, size);
855 out_err:
856 	return dst;
857 }
858 
user_copy(void * dst,const void * src,size_t size,bool to_user)859 static int user_copy(void *dst, const void *src, size_t size, bool to_user)
860 {
861 	int ret = EFAULT;
862 
863 	/* Does the caller in user mode have access to this memory? */
864 	if (to_user ? K_SYSCALL_MEMORY_WRITE(dst, size) :
865 			K_SYSCALL_MEMORY_READ(src, size)) {
866 		goto out_err;
867 	}
868 
869 	(void)memcpy(dst, src, size);
870 	ret = 0;
871 out_err:
872 	return ret;
873 }
874 
k_usermode_from_copy(void * dst,const void * src,size_t size)875 int k_usermode_from_copy(void *dst, const void *src, size_t size)
876 {
877 	return user_copy(dst, src, size, false);
878 }
879 
k_usermode_to_copy(void * dst,const void * src,size_t size)880 int k_usermode_to_copy(void *dst, const void *src, size_t size)
881 {
882 	return user_copy(dst, src, size, true);
883 }
884 
k_usermode_string_alloc_copy(const char * src,size_t maxlen)885 char *k_usermode_string_alloc_copy(const char *src, size_t maxlen)
886 {
887 	size_t actual_len;
888 	int err;
889 	char *ret = NULL;
890 
891 	actual_len = k_usermode_string_nlen(src, maxlen, &err);
892 	if (err != 0) {
893 		goto out;
894 	}
895 	if (actual_len == maxlen) {
896 		/* Not NULL terminated */
897 		LOG_ERR("string too long %p (%zu)", src, actual_len);
898 		goto out;
899 	}
900 	if (size_add_overflow(actual_len, 1, &actual_len)) {
901 		LOG_ERR("overflow");
902 		goto out;
903 	}
904 
905 	ret = k_usermode_alloc_from_copy(src, actual_len);
906 
907 	/* Someone may have modified the source string during the above
908 	 * checks. Ensure what we actually copied is still terminated
909 	 * properly.
910 	 */
911 	if (ret != NULL) {
912 		ret[actual_len - 1U] = '\0';
913 	}
914 out:
915 	return ret;
916 }
917 
k_usermode_string_copy(char * dst,const char * src,size_t maxlen)918 int k_usermode_string_copy(char *dst, const char *src, size_t maxlen)
919 {
920 	size_t actual_len;
921 	int ret, err;
922 
923 	actual_len = k_usermode_string_nlen(src, maxlen, &err);
924 	if (err != 0) {
925 		ret = EFAULT;
926 		goto out;
927 	}
928 	if (actual_len == maxlen) {
929 		/* Not NULL terminated */
930 		LOG_ERR("string too long %p (%zu)", src, actual_len);
931 		ret = EINVAL;
932 		goto out;
933 	}
934 	if (size_add_overflow(actual_len, 1, &actual_len)) {
935 		LOG_ERR("overflow");
936 		ret = EINVAL;
937 		goto out;
938 	}
939 
940 	ret = k_usermode_from_copy(dst, src, actual_len);
941 
942 	/* See comment above in k_usermode_string_alloc_copy() */
943 	dst[actual_len - 1] = '\0';
944 out:
945 	return ret;
946 }
947 
948 /*
949  * Application memory region initialization
950  */
951 
952 extern char __app_shmem_regions_start[];
953 extern char __app_shmem_regions_end[];
954 
app_shmem_bss_zero(void)955 static int app_shmem_bss_zero(void)
956 {
957 	struct z_app_region *region, *end;
958 
959 
960 	end = (struct z_app_region *)&__app_shmem_regions_end[0];
961 	region = (struct z_app_region *)&__app_shmem_regions_start[0];
962 
963 	for ( ; region < end; region++) {
964 #if defined(CONFIG_DEMAND_PAGING) && !defined(CONFIG_LINKER_GENERIC_SECTIONS_PRESENT_AT_BOOT)
965 		/* When BSS sections are not present at boot, we need to wait for
966 		 * paging mechanism to be initialized before we can zero out BSS.
967 		 */
968 		extern bool z_sys_post_kernel;
969 		bool do_clear = z_sys_post_kernel;
970 
971 		/* During pre-kernel init, z_sys_post_kernel == false, but
972 		 * with pinned rodata region, so clear. Otherwise skip.
973 		 * In post-kernel init, z_sys_post_kernel == true,
974 		 * skip those in pinned rodata region as they have already
975 		 * been cleared and possibly already in use. Otherwise clear.
976 		 */
977 		if (((uint8_t *)region->bss_start >= (uint8_t *)_app_smem_pinned_start) &&
978 		    ((uint8_t *)region->bss_start < (uint8_t *)_app_smem_pinned_end)) {
979 			do_clear = !do_clear;
980 		}
981 
982 		if (do_clear)
983 #endif /* CONFIG_DEMAND_PAGING && !CONFIG_LINKER_GENERIC_SECTIONS_PRESENT_AT_BOOT */
984 		{
985 			(void)memset(region->bss_start, 0, region->bss_size);
986 		}
987 	}
988 
989 	return 0;
990 }
991 
992 SYS_INIT_NAMED(app_shmem_bss_zero_pre, app_shmem_bss_zero,
993 	       PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
994 
995 #if defined(CONFIG_DEMAND_PAGING) && !defined(CONFIG_LINKER_GENERIC_SECTIONS_PRESENT_AT_BOOT)
996 /* When BSS sections are not present at boot, we need to wait for
997  * paging mechanism to be initialized before we can zero out BSS.
998  */
999 SYS_INIT_NAMED(app_shmem_bss_zero_post, app_shmem_bss_zero,
1000 	       POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
1001 #endif /* CONFIG_DEMAND_PAGING && !CONFIG_LINKER_GENERIC_SECTIONS_PRESENT_AT_BOOT */
1002 
1003 /*
1004  * Default handlers if otherwise unimplemented
1005  */
1006 
handler_bad_syscall(uintptr_t bad_id,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4,uintptr_t arg5,uintptr_t arg6,void * ssf)1007 static uintptr_t handler_bad_syscall(uintptr_t bad_id, uintptr_t arg2,
1008 				     uintptr_t arg3, uintptr_t arg4,
1009 				     uintptr_t arg5, uintptr_t arg6,
1010 				     void *ssf)
1011 {
1012 	ARG_UNUSED(arg2);
1013 	ARG_UNUSED(arg3);
1014 	ARG_UNUSED(arg4);
1015 	ARG_UNUSED(arg5);
1016 	ARG_UNUSED(arg6);
1017 
1018 	LOG_ERR("Bad system call id %" PRIuPTR " invoked", bad_id);
1019 	arch_syscall_oops(ssf);
1020 	CODE_UNREACHABLE; /* LCOV_EXCL_LINE */
1021 }
1022 
handler_no_syscall(uintptr_t arg1,uintptr_t arg2,uintptr_t arg3,uintptr_t arg4,uintptr_t arg5,uintptr_t arg6,void * ssf)1023 static uintptr_t handler_no_syscall(uintptr_t arg1, uintptr_t arg2,
1024 				    uintptr_t arg3, uintptr_t arg4,
1025 				    uintptr_t arg5, uintptr_t arg6, void *ssf)
1026 {
1027 	ARG_UNUSED(arg1);
1028 	ARG_UNUSED(arg2);
1029 	ARG_UNUSED(arg3);
1030 	ARG_UNUSED(arg4);
1031 	ARG_UNUSED(arg5);
1032 	ARG_UNUSED(arg6);
1033 
1034 	LOG_ERR("Unimplemented system call");
1035 	arch_syscall_oops(ssf);
1036 	CODE_UNREACHABLE; /* LCOV_EXCL_LINE */
1037 }
1038 
1039 #include <zephyr/syscall_dispatch.c>
1040