1// Copyright 2018 The Fuchsia Authors
2//
3// Use of this source code is governed by a MIT-style
4// license that can be found in the LICENSE file or at
5// https://opensource.org/licenses/MIT
6
7#include <err.h>
8#include <inttypes.h>
9
10#include <lib/counters.h>
11#include <lib/ktrace.h>
12
13#include <object/handle.h>
14#include <object/profile_dispatcher.h>
15
16#include <zircon/syscalls/resource.h>
17#include <zircon/types.h>
18
19#include <object/resource.h>
20
21#include <fbl/ref_ptr.h>
22#include <fbl/type_support.h>
23
24#include "priv.h"
25
26KCOUNTER(profile_create, "kernel.profile.create");
27KCOUNTER(profile_set,    "kernel.profile.set");
28
29
30zx_status_t sys_profile_create(zx_handle_t resource,
31                               user_in_ptr<const zx_profile_info_t> user_profile_info,
32                               user_out_handle* out) {
33    // TODO(cpu): check job policy.
34
35    zx_status_t status = validate_resource(resource, ZX_RSRC_KIND_ROOT);
36    if (status != ZX_OK)
37        return status;
38
39    zx_profile_info_t profile_info;
40    status = user_profile_info.copy_from_user(&profile_info);
41    if (status != ZX_OK)
42        return status;
43
44    fbl::RefPtr<Dispatcher> dispatcher;
45    zx_rights_t rights;
46    status = ProfileDispatcher::Create(profile_info, &dispatcher, &rights);
47    if (status != ZX_OK)
48        return status;
49
50    return out->make(fbl::move(dispatcher), rights);
51}
52
53zx_status_t sys_object_set_profile(zx_handle_t handle,
54                                   zx_handle_t profile_handle,
55                                   uint32_t options) {
56    auto up = ProcessDispatcher::GetCurrent();
57
58    // TODO(cpu): support more than thread objects, and actually do something.
59
60    fbl::RefPtr<ThreadDispatcher> thread;
61    auto status = up->GetDispatcherWithRights(handle, ZX_RIGHT_MANAGE_THREAD, &thread);
62    if (status != ZX_OK)
63        return status;
64
65    fbl::RefPtr<ProfileDispatcher> profile;
66    zx_status_t result =
67        up->GetDispatcherWithRights(profile_handle, ZX_RIGHT_APPLY_PROFILE, &profile);
68    if (result != ZX_OK)
69        return result;
70
71    return profile->ApplyProfile(fbl::move(thread));
72}
73
74