repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
blueboxd/chromium-legacy
components/app_restore/desk_template_read_handler.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_APP_RESTORE_DESK_TEMPLATE_READ_HANDLER_H_ #define COMPONENTS_APP_RESTORE_DESK_TEMPLATE_READ_HANDLER_H_ #include <memory> #include <string> #include "base/component_export.h" #include "components/app_restore/app_restore_arc_info.h" #include "components/app_restore/arc_read_handler.h" namespace app_restore { struct AppLaunchInfo; class RestoreData; struct WindowInfo; // DeskTemplateReadHandler is responsible for receiving `RestoreData` from desks // storage. It keeps a copy of restore data during a desk template launch and // provides APIs for reading window info of the launched applications. class COMPONENT_EXPORT(APP_RESTORE) DeskTemplateReadHandler : public ArcReadHandler::Delegate, public AppRestoreArcInfo::Observer { public: DeskTemplateReadHandler(); DeskTemplateReadHandler(const DeskTemplateReadHandler&) = delete; DeskTemplateReadHandler& operator=(const DeskTemplateReadHandler&) = delete; ~DeskTemplateReadHandler() override; static DeskTemplateReadHandler* Get(); RestoreData* restore_data() { return restore_data_.get(); } // Sets the `restore_data` for a launch session. `restore_data` can be // nullptr, which signifies that a launch session is over. Creates // `arc_read_handler_` if necessary, which is a helper class for dealing with // ARC apps. void SetRestoreData(std::unique_ptr<RestoreData> restore_data); // Gets the window information for `restore_window_id`. std::unique_ptr<WindowInfo> GetWindowInfo(int restore_window_id); // Fetches the restore id for the window from RestoreData for the given // `app_id`. `app_id` should be a Chrome app id. int32_t FetchRestoreWindowId(const std::string& app_id); // Modifies the `restore_data_` to set the next restore window id for the // chrome app with `app_id`. void SetNextRestoreWindowIdForChromeApp(const std::string& app_id); // ArcReadHandler::Delegate: std::unique_ptr<AppLaunchInfo> GetAppLaunchInfo( const base::FilePath& profile_path, const std::string& app_id, int32_t restore_window_id) override; std::unique_ptr<WindowInfo> GetWindowInfo(const base::FilePath& profile_path, const std::string& app_id, int32_t restore_window_id) override; void RemoveAppRestoreData(const base::FilePath& profile_path, const std::string& app_id, int32_t restore_window_id) override; // AppRestoreArcInfo::Observer: void OnTaskCreated(const std::string& app_id, int32_t task_id, int32_t session_id) override; void OnTaskDestroyed(int32_t task_id) override; // Generates the ARC session id (1,000,000,001 - INT_MAX) for restored ARC // apps. int32_t GetArcSessionId(); // Sets `arc_session_id` for `window_id`. `arc session id` is assigned when // ARC apps are restored. void SetArcSessionIdForWindowId(int32_t arc_session_id, int32_t window_id); // Returns the restore window id for the ARC app's `task_id`. int32_t GetArcRestoreWindowIdForTaskId(int32_t task_id); // Returns the restore window id for the ARC app's `session_id`. int32_t GetArcRestoreWindowIdForSessionId(int32_t session_id); private: // The restore data read from desk storage. Empty when no launch is underway. std::unique_ptr<RestoreData> restore_data_; // Helper that is created if an ARC app is launched. This class contains some // ARC specific logic needed to launch ARC apps. std::unique_ptr<ArcReadHandler> arc_read_handler_; }; } // namespace app_restore #endif // COMPONENTS_APP_RESTORE_DESK_TEMPLATE_READ_HANDLER_H_
blueboxd/chromium-legacy
content/browser/aggregation_service/aggregation_service_test_utils.h
<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_AGGREGATION_SERVICE_AGGREGATION_SERVICE_TEST_UTILS_H_ #define CONTENT_BROWSER_AGGREGATION_SERVICE_AGGREGATION_SERVICE_TEST_UTILS_H_ #include <stdint.h> #include <map> #include <ostream> #include <string> #include <vector> #include "base/threading/sequence_bound.h" #include "content/browser/aggregation_service/aggregatable_report.h" #include "content/browser/aggregation_service/aggregatable_report_manager.h" #include "content/browser/aggregation_service/aggregation_service_key_fetcher.h" #include "content/browser/aggregation_service/aggregation_service_key_storage.h" #include "content/browser/aggregation_service/public_key.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/boringssl/src/include/openssl/hpke.h" #include "url/origin.h" namespace base { class Clock; } // namespace base namespace content { namespace aggregation_service { struct TestHpkeKey { // Public-private key pair. EVP_HPKE_KEY full_hpke_key; // Contains a copy of the public key of `full_hpke_key`. PublicKey public_key; // Contains a base64-encoded copy of `public_key.key` std::string base64_encoded_public_key; }; testing::AssertionResult PublicKeysEqual(const std::vector<PublicKey>& expected, const std::vector<PublicKey>& actual); testing::AssertionResult AggregatableReportsEqual( const AggregatableReport& expected, const AggregatableReport& actual); testing::AssertionResult ReportRequestsEqual( const AggregatableReportRequest& expected, const AggregatableReportRequest& actual); testing::AssertionResult PayloadContentsEqual( const AggregationServicePayloadContents& expected, const AggregationServicePayloadContents& actual); testing::AssertionResult SharedInfoEqual( const AggregatableReportSharedInfo& expected, const AggregatableReportSharedInfo& actual); AggregatableReportRequest CreateExampleRequest(); AggregatableReportRequest CloneReportRequest( const AggregatableReportRequest& request); AggregatableReport CloneAggregatableReport(const AggregatableReport& report); // Generates a public-private key pair for HPKE and also constructs a PublicKey // object for use in assembler methods. TestHpkeKey GenerateKey(std::string key_id = "example_id"); } // namespace aggregation_service // The strings "ABCD1234" and "EFGH5678", Base64-decoded to bytes. Note that // both of these strings are valid Base64. const std::vector<uint8_t> kABCD1234AsBytes = {0, 16, 131, 215, 109, 248}; const std::vector<uint8_t> kEFGH5678AsBytes = {16, 81, 135, 231, 174, 252}; class TestAggregatableReportManager : public AggregatableReportManager { public: explicit TestAggregatableReportManager(const base::Clock* clock); TestAggregatableReportManager(const TestAggregatableReportManager& other) = delete; TestAggregatableReportManager& operator=( const TestAggregatableReportManager& other) = delete; ~TestAggregatableReportManager() override; // AggregatableReportManager: const base::SequenceBound<content::AggregationServiceKeyStorage>& GetKeyStorage() override; private: base::SequenceBound<content::AggregationServiceKeyStorage> storage_; }; class TestAggregationServiceKeyFetcher : public AggregationServiceKeyFetcher { public: TestAggregationServiceKeyFetcher(); ~TestAggregationServiceKeyFetcher() override; // AggregationServiceKeyFetcher: void GetPublicKey(const url::Origin& origin, FetchCallback callback) override; // Triggers a response for each fetch for `origin`, throwing an error if no // such fetches exist. void TriggerPublicKeyResponse(const url::Origin& origin, absl::optional<PublicKey> key, PublicKeyFetchStatus status); void TriggerPublicKeyResponseForAllOrigins(absl::optional<PublicKey> key, PublicKeyFetchStatus status); bool HasPendingCallbacks(); private: std::map<url::Origin, std::vector<FetchCallback>> callbacks_; }; // A simple class for mocking CreateFromRequestAndPublicKeys(). class TestAggregatableReportProvider : public AggregatableReport::Provider { public: TestAggregatableReportProvider(); ~TestAggregatableReportProvider() override; absl::optional<AggregatableReport> CreateFromRequestAndPublicKeys( AggregatableReportRequest report_request, std::vector<PublicKey> public_keys) const override; int num_calls() const { return num_calls_; } const AggregatableReportRequest& PreviousRequest() const { EXPECT_TRUE(previous_request_.has_value()); return previous_request_.value(); } const std::vector<PublicKey>& PreviousPublicKeys() const { EXPECT_TRUE(previous_request_.has_value()); return previous_public_keys_; } void set_report_to_return( absl::optional<AggregatableReport> report_to_return) { report_to_return_ = std::move(report_to_return); } private: absl::optional<AggregatableReport> report_to_return_; // The following are mutable to allow `CreateFromRequestAndPublicKeys()` to be // const. // Number of times `CreateFromRequestAndPublicKeys()` is called. mutable int num_calls_ = 0; // `absl::nullopt` iff `num_calls_` is 0. mutable absl::optional<AggregatableReportRequest> previous_request_; // Empty if `num_calls_` is 0. mutable std::vector<PublicKey> previous_public_keys_; }; // Only used for logging in tests. std::ostream& operator<<( std::ostream& out, const AggregationServicePayloadContents::Operation& operation); std::ostream& operator<<( std::ostream& out, const AggregationServicePayloadContents::ProcessingType& processing_type); } // namespace content #endif // CONTENT_BROWSER_AGGREGATION_SERVICE_AGGREGATION_SERVICE_TEST_UTILS_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_TEXT_FRAGMENT_ANCHOR_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_TEXT_FRAGMENT_ANCHOR_H_ #include "third_party/blink/public/mojom/loader/same_document_navigation_type.mojom-blink.h" #include "third_party/blink/public/web/web_frame_load_type.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/editing/forward.h" #include "third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.h" #include "third_party/blink/renderer/core/page/scrolling/fragment_anchor.h" #include "third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h" #include "third_party/blink/renderer/core/page/scrolling/text_fragment_finder.h" #include "third_party/blink/renderer/core/scroll/scroll_types.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { class DocumentLoader; class LocalFrame; class KURL; class TextDirective; class CORE_EXPORT TextFragmentAnchor final : public FragmentAnchor, public TextFragmentFinder::Client { public: // When a document is loaded, this method will be called to see if it meets // the criteria to generate a new permission token (at a high level it means: // did the user initiate the navigation?). This token can then be used to // invoke the text fragment anchor later during loading or propagated across // a redirect so that the real destination can invoke a text fragment. static bool GenerateNewToken(const DocumentLoader&); // Same as above but for same-document navigations. These require a bit of // care since DocumentLoader's state is based on the initial document load. // In this case, we also avoid generating the token unless the new URL has a // text fragment in it (and thus it'll be consumed immediately). static bool GenerateNewTokenForSameDocument( const DocumentLoader&, WebFrameLoadType load_type, mojom::blink::SameDocumentNavigationType same_document_navigation_type); static TextFragmentAnchor* TryCreate(const KURL& url, LocalFrame& frame, bool should_scroll); TextFragmentAnchor(HeapVector<Member<TextDirective>>& text_directives, LocalFrame& frame, bool should_scroll); TextFragmentAnchor(const TextFragmentAnchor&) = delete; TextFragmentAnchor& operator=(const TextFragmentAnchor&) = delete; ~TextFragmentAnchor() override = default; bool Invoke() override; void Installed() override; void DidScroll(mojom::blink::ScrollType type) override; void PerformPreRafActions() override; // Removes text match highlights if any highlight is in view. bool Dismiss() override; void SetTickClockForTesting(const base::TickClock* tick_clock); void Trace(Visitor*) const override; // TextFragmentFinder::Client interface void DidFindMatch(const RangeInFlatTree& range, const TextFragmentAnchorMetrics::Match match_metrics, bool is_unique) override; void NoMatchFound() override {} static bool ShouldDismissOnScrollOrClick(); using DirectiveFinderPair = std::pair<Member<TextDirective>, Member<TextFragmentFinder>>; const HeapVector<DirectiveFinderPair>& DirectiveFinderPairs() const { return directive_finder_pairs_; } bool IsTextFragmentAnchor() override { return true; } private: // Called when the search is finished. Reports metrics and activates the // element fragment anchor if we didn't find a match. void DidFinishSearch(); void ApplyTargetToCommonAncestor(const EphemeralRangeInFlatTree& range); void FireBeforeMatchEvent(Element* element); bool HasSearchEngineSource(); // This keeps track of each TextDirective and its associated // TextFragmentFinder. The directive is the DOM object exposed to JS that's // parsed from the URL while the finder is the object responsible for // performing the search for the specified text in the Document. HeapVector<DirectiveFinderPair> directive_finder_pairs_; Member<LocalFrame> frame_; bool search_finished_ = false; // Whether the user has scrolled the page. bool user_scrolled_ = false; // Indicates that we should scroll into view the first match that we find, set // to true each time the anchor is invoked if the user hasn't scrolled. bool first_match_needs_scroll_ = false; // Whether we successfully scrolled into view a match at least once, used for // metrics reporting. bool did_scroll_into_view_ = false; // Whether we found a match. Used to determine if we should activate the // element fragment anchor at the end of searching. bool did_find_match_ = false; // If the text fragment anchor is defined as a fragment directive and we don't // find a match, we fall back to the element anchor if it is present. Member<ElementFragmentAnchor> element_fragment_anchor_; // Whether the text fragment anchor has been dismissed yet. This should be // kept alive until dismissed so we can remove text highlighting. bool dismissed_ = false; // Whether we should scroll the anchor into view. This will be false for // history navigations and reloads, where we want to restore the highlight but // not scroll into view again. bool should_scroll_ = false; // Whether the page has been made visible. Used to ensure we wait until the // page has been made visible to start matching, to help prevent brute force // search attacks. bool page_has_been_visible_ = false; // Whether we performed a non-zero scroll to scroll a match into view. Used // to determine whether the user subsequently scrolls back to the top. bool did_non_zero_scroll_ = false; // Whether PerformPreRafActions should run at the next rAF. bool needs_perform_pre_raf_actions_ = false; // Whether a text fragment finder was run. bool has_performed_first_text_search_ = false; enum BeforematchState { kNoMatchFound, // DidFindMatch has not been called. kEventQueued, // Beforematch event has been queued, but not fired yet. kFiredEvent // Beforematch event has been fired. } beforematch_state_ = kNoMatchFound; Member<TextFragmentAnchorMetrics> metrics_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_TEXT_FRAGMENT_ANCHOR_H_
blueboxd/chromium-legacy
ui/ozone/platform/wayland/host/wayland_connection.h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_CONNECTION_H_ #define UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_CONNECTION_H_ #include <time.h> #include <memory> #include <string> #include <vector> #include "base/containers/flat_map.h" #include "base/time/time.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/display/tablet_state.h" #include "ui/events/event.h" #include "ui/ozone/platform/wayland/common/wayland_object.h" #include "ui/ozone/platform/wayland/host/wayland_clipboard.h" #include "ui/ozone/platform/wayland/host/wayland_data_drag_controller.h" #include "ui/ozone/platform/wayland/host/wayland_data_source.h" #include "ui/ozone/platform/wayland/host/wayland_serial_tracker.h" #include "ui/ozone/platform/wayland/host/wayland_window_manager.h" struct wl_cursor; struct wl_event_queue; namespace gfx { class Point; } namespace wl { class WaylandProxy; } namespace ui { class DeviceHotplugEventObserver; class OrgKdeKwinIdle; class SurfaceAugmenter; class WaylandBufferManagerHost; class WaylandCursor; class WaylandCursorBufferListener; class WaylandDrm; class WaylandEventSource; class WaylandKeyboard; class WaylandOutputManager; class WaylandPointer; class WaylandShm; class WaylandTouch; class WaylandZAuraShell; class WaylandZcrCursorShapes; class WaylandZwpPointerConstraints; class WaylandZwpPointerGestures; class WaylandZwpRelativePointerManager; class WaylandZwpLinuxDmabuf; class WaylandDataDeviceManager; class WaylandCursorPosition; class WaylandWindowDragController; class GtkPrimarySelectionDeviceManager; class GtkShell1; class ZwpIdleInhibitManager; class ZwpPrimarySelectionDeviceManager; class XdgForeignWrapper; class OverlayPrioritizer; // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. // // Append new shells before kMaxValue and update LinuxWaylandShell // in tools/metrics/histograms/enums.xml accordingly. // // See also tools/metrics/histograms/README.md#enum-histograms enum class UMALinuxWaylandShell { kZauraShell = 0, kGtkShell1 = 1, kOrgKdePlasmaShell = 2, kXdgWmBase = 3, kXdgShellV6 = 4, kZwlrLayerShellV1 = 5, kMaxValue = kZwlrLayerShellV1, }; void ReportShellUMA(UMALinuxWaylandShell shell); class WaylandConnection { public: WaylandConnection(); WaylandConnection(const WaylandConnection&) = delete; WaylandConnection& operator=(const WaylandConnection&) = delete; ~WaylandConnection(); bool Initialize(); void RegisterGlobalObjectFactory(const char* interface_name, wl::GlobalObjectFactory factory); // Schedules a flush of the Wayland connection. void ScheduleFlush(); // Calls wl_display_roundtrip_queue. Might be required during initialization // of some objects that should block until they are initialized. void RoundTripQueue(); // Sets a callback that that shutdowns the browser in case of unrecoverable // error. Called by WaylandEventWatcher. void SetShutdownCb(base::OnceCallback<void()> shutdown_cb); // A correct display must be chosen when creating objects or calling // roundrips. That is, all the methods that deal with polling, pulling event // queues, etc, must use original display. All the other methods that create // various wayland objects must use |display_wrapper_| so that the new objects // are associated with the correct event queue. Otherwise, they will use a // default event queue, which we do not use. See the comment below about the // |event_queue_|. wl_display* display() const { return display_.get(); } wl_display* display_wrapper() const { return reinterpret_cast<wl_display*>(wrapped_display_.get()); } wl_compositor* compositor() const { return compositor_.get(); } // The server version of the compositor interface (might be higher than the // version binded). uint32_t compositor_version() const { return compositor_version_; } wl_subcompositor* subcompositor() const { return subcompositor_.get(); } wp_viewporter* viewporter() const { return viewporter_.get(); } zcr_alpha_compositing_v1* alpha_compositing() const { return alpha_compositing_.get(); } xdg_wm_base* shell() const { return shell_.get(); } zxdg_shell_v6* shell_v6() const { return shell_v6_.get(); } wl_seat* seat() const { return seat_.get(); } wp_presentation* presentation() const { return presentation_.get(); } zwp_text_input_manager_v1* text_input_manager_v1() const { return text_input_manager_v1_.get(); } zcr_text_input_extension_v1* text_input_extension_v1() const { return text_input_extension_v1_.get(); } zwp_linux_explicit_synchronization_v1* linux_explicit_synchronization_v1() const { return linux_explicit_synchronization_.get(); } zxdg_decoration_manager_v1* xdg_decoration_manager_v1() const { return xdg_decoration_manager_.get(); } zcr_extended_drag_v1* extended_drag_v1() const { return extended_drag_v1_.get(); } zxdg_output_manager_v1* xdg_output_manager_v1() const { return xdg_output_manager_.get(); } void SetPlatformCursor(wl_cursor* cursor_data, int buffer_scale); void SetCursorBufferListener(WaylandCursorBufferListener* listener); void SetCursorBitmap(const std::vector<SkBitmap>& bitmaps, const gfx::Point& hotspot_in_dips, int buffer_scale); WaylandEventSource* event_source() const { return event_source_.get(); } // Returns the current touch, which may be null. WaylandTouch* touch() const { return touch_.get(); } // Returns the current pointer, which may be null. WaylandPointer* pointer() const { return pointer_.get(); } // Returns the current keyboard, which may be null. WaylandKeyboard* keyboard() const { return keyboard_.get(); } WaylandClipboard* clipboard() const { return clipboard_.get(); } WaylandOutputManager* wayland_output_manager() const { return wayland_output_manager_.get(); } // Returns the cursor position, which may be null. WaylandCursorPosition* wayland_cursor_position() const { return wayland_cursor_position_.get(); } WaylandBufferManagerHost* buffer_manager_host() const { return buffer_manager_host_.get(); } WaylandZAuraShell* zaura_shell() const { return zaura_shell_.get(); } WaylandZcrCursorShapes* zcr_cursor_shapes() const { return zcr_cursor_shapes_.get(); } WaylandZwpLinuxDmabuf* zwp_dmabuf() const { return zwp_dmabuf_.get(); } WaylandDrm* drm() const { return drm_.get(); } WaylandShm* shm() const { return shm_.get(); } WaylandWindowManager* wayland_window_manager() { return &wayland_window_manager_; } WaylandDataDeviceManager* data_device_manager() const { return data_device_manager_.get(); } GtkPrimarySelectionDeviceManager* gtk_primary_selection_device_manager() const { return gtk_primary_selection_device_manager_.get(); } GtkShell1* gtk_shell1() { return gtk_shell1_.get(); } OrgKdeKwinIdle* org_kde_kwin_idle() { return org_kde_kwin_idle_.get(); } ZwpPrimarySelectionDeviceManager* zwp_primary_selection_device_manager() const { return zwp_primary_selection_device_manager_.get(); } WaylandDataDragController* data_drag_controller() const { return data_drag_controller_.get(); } WaylandWindowDragController* window_drag_controller() const { return window_drag_controller_.get(); } WaylandZwpPointerConstraints* wayland_zwp_pointer_constraints() const { return wayland_zwp_pointer_constraints_.get(); } WaylandZwpRelativePointerManager* wayland_zwp_relative_pointer_manager() const { return wayland_zwp_relative_pointer_manager_.get(); } XdgForeignWrapper* xdg_foreign() const { return xdg_foreign_.get(); } ZwpIdleInhibitManager* zwp_idle_inhibit_manager() const { return zwp_idle_inhibit_manager_.get(); } OverlayPrioritizer* overlay_prioritizer() const { return overlay_prioritizer_.get(); } SurfaceAugmenter* surface_augmenter() const { return surface_augmenter_.get(); } // Returns whether protocols that support setting window geometry are // available. bool SupportsSetWindowGeometry() const; // Returns true when dragging is entered or started. bool IsDragInProgress() const; // Creates a new wl_surface. wl::Object<wl_surface> CreateSurface(); // base::TimeTicks::Now() in posix uses CLOCK_MONOTONIC, wp_presentation // timestamps are in clk_id sent in wp_presentation.clock_id event. This // converts wp_presentation timestamp to base::TimeTicks. // The approximation relies on presentation timestamp to be close to current // time. The further it is from current time and the bigger the speed // difference between the two clock domains, the bigger the conversion error. // Conversion error due to system load is biased and unbounded. base::TimeTicks ConvertPresentationTime(uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec); const std::vector<std::pair<std::string, uint32_t>>& available_globals() const { return available_globals_; } bool surface_submission_in_pixel_coordinates() const { return surface_submission_in_pixel_coordinates_; } void set_surface_submission_in_pixel_coordinates(bool enabled) { surface_submission_in_pixel_coordinates_ = enabled; } wl::SerialTracker& serial_tracker() { return serial_tracker_; } void set_tablet_layout_state(display::TabletState tablet_layout_state) { tablet_layout_state_ = tablet_layout_state; } bool GetTabletMode() { return tablet_layout_state_ == display::TabletState::kInTabletMode || tablet_layout_state_ == display::TabletState::kEnteringTabletMode; } private: friend class WaylandConnectionTestApi; // All global Wayland objects are friends of the Wayland connection. // Conceptually, this is correct: globals are owned by the connection and are // accessed via it, so they are essentially parts of it. Also this friendship // makes it possible to avoid exposing setters for all those global objects: // these setters would only be needed by the globals but would be visible to // everyone. friend class GtkPrimarySelectionDeviceManager; friend class GtkShell1; friend class OrgKdeKwinIdle; friend class OverlayPrioritizer; friend class SurfaceAugmenter; friend class WaylandDataDeviceManager; friend class WaylandDrm; friend class WaylandOutput; friend class WaylandShm; friend class WaylandZAuraShell; friend class WaylandZwpLinuxDmabuf; friend class WaylandZwpPointerConstraints; friend class WaylandZwpPointerGestures; friend class WaylandZwpRelativePointerManager; friend class WaylandZcrCursorShapes; friend class XdgForeignWrapper; friend class ZwpIdleInhibitManager; friend class ZwpPrimarySelectionDeviceManager; void Flush(); void UpdateInputDevices(wl_seat* seat, uint32_t capabilities); // Initialize data-related objects if required protocol objects are already // in place, i.e: wl_seat and wl_data_device_manager. void CreateDataObjectsIfReady(); // Creates WaylandKeyboard with the currently acquired protocol objects, if // possible. Returns true iff WaylandKeyboard was created. bool CreateKeyboard(); DeviceHotplugEventObserver* GetHotplugEventObserver(); // wl_registry_listener static void Global(void* data, wl_registry* registry, uint32_t name, const char* interface, uint32_t version); static void GlobalRemove(void* data, wl_registry* registry, uint32_t name); // wl_seat_listener static void Capabilities(void* data, wl_seat* seat, uint32_t capabilities); static void Name(void* data, wl_seat* seat, const char* name); // zxdg_shell_v6_listener static void PingV6(void* data, zxdg_shell_v6* zxdg_shell_v6, uint32_t serial); // xdg_wm_base_listener static void Ping(void* data, xdg_wm_base* shell, uint32_t serial); // xdg_wm_base_listener static void ClockId(void* data, wp_presentation* shell_v6, uint32_t clk_id); base::flat_map<std::string, wl::GlobalObjectFactory> global_object_factories_; uint32_t compositor_version_ = 0; wl::Object<wl_display> display_; wl::Object<wl_proxy> wrapped_display_; wl::Object<wl_event_queue> event_queue_; wl::Object<wl_registry> registry_; wl::Object<wl_compositor> compositor_; wl::Object<wl_subcompositor> subcompositor_; wl::Object<wl_seat> seat_; wl::Object<xdg_wm_base> shell_; wl::Object<zxdg_shell_v6> shell_v6_; wl::Object<wp_presentation> presentation_; wl::Object<wp_viewporter> viewporter_; wl::Object<zcr_alpha_compositing_v1> alpha_compositing_; wl::Object<zcr_keyboard_extension_v1> keyboard_extension_v1_; wl::Object<zwp_text_input_manager_v1> text_input_manager_v1_; wl::Object<zcr_text_input_extension_v1> text_input_extension_v1_; wl::Object<zwp_linux_explicit_synchronization_v1> linux_explicit_synchronization_; wl::Object<zxdg_decoration_manager_v1> xdg_decoration_manager_; wl::Object<zcr_extended_drag_v1> extended_drag_v1_; wl::Object<zxdg_output_manager_v1> xdg_output_manager_; // Event source instance. Must be declared before input objects so it // outlives them so thus being able to properly handle their destruction. std::unique_ptr<WaylandEventSource> event_source_; // Input device objects. std::unique_ptr<WaylandKeyboard> keyboard_; std::unique_ptr<WaylandPointer> pointer_; std::unique_ptr<WaylandTouch> touch_; std::unique_ptr<WaylandCursor> cursor_; std::unique_ptr<WaylandDataDeviceManager> data_device_manager_; std::unique_ptr<WaylandOutputManager> wayland_output_manager_; std::unique_ptr<WaylandCursorPosition> wayland_cursor_position_; std::unique_ptr<WaylandZAuraShell> zaura_shell_; std::unique_ptr<WaylandZcrCursorShapes> zcr_cursor_shapes_; std::unique_ptr<WaylandZwpPointerConstraints> wayland_zwp_pointer_constraints_; std::unique_ptr<WaylandZwpRelativePointerManager> wayland_zwp_relative_pointer_manager_; std::unique_ptr<WaylandZwpPointerGestures> wayland_zwp_pointer_gestures_; std::unique_ptr<WaylandZwpLinuxDmabuf> zwp_dmabuf_; std::unique_ptr<WaylandDrm> drm_; std::unique_ptr<WaylandShm> shm_; std::unique_ptr<WaylandBufferManagerHost> buffer_manager_host_; std::unique_ptr<XdgForeignWrapper> xdg_foreign_; std::unique_ptr<ZwpIdleInhibitManager> zwp_idle_inhibit_manager_; std::unique_ptr<OverlayPrioritizer> overlay_prioritizer_; std::unique_ptr<SurfaceAugmenter> surface_augmenter_; // Clipboard-related objects. |clipboard_| must be declared after all // DeviceManager instances it depends on, otherwise tests may crash with // UAFs while attempting to access already destroyed manager pointers. std::unique_ptr<GtkPrimarySelectionDeviceManager> gtk_primary_selection_device_manager_; std::unique_ptr<ZwpPrimarySelectionDeviceManager> zwp_primary_selection_device_manager_; std::unique_ptr<WaylandClipboard> clipboard_; std::unique_ptr<GtkShell1> gtk_shell1_; // Objects specific to KDE Plasma desktop environment. std::unique_ptr<OrgKdeKwinIdle> org_kde_kwin_idle_; std::unique_ptr<WaylandDataDragController> data_drag_controller_; std::unique_ptr<WaylandWindowDragController> window_drag_controller_; // Describes the clock domain that wp_presentation timestamps are in. uint32_t presentation_clk_id_ = CLOCK_MONOTONIC; // Helper class that lets input emulation access some data of objects // that Wayland holds. For example, wl_surface and others. It's only // created when platform window test config is set. std::unique_ptr<wl::WaylandProxy> wayland_proxy_; // Manages Wayland windows. WaylandWindowManager wayland_window_manager_; WaylandCursorBufferListener* listener_ = nullptr; // The current window table mode layout state. display::TabletState tablet_layout_state_ = display::TabletState::kInClamshellMode; bool scheduled_flush_ = false; // Surfaces are submitted in pixel coordinates. Their buffer scales are always // advertised to server as 1, and the scale via vp_viewporter won't be // applied. The server will be responsible to scale the buffers to the right // sizes. bool surface_submission_in_pixel_coordinates_ = false; wl::SerialTracker serial_tracker_; // Global Wayland interfaces available in the current session, with their // versions. std::vector<std::pair<std::string, uint32_t>> available_globals_; }; } // namespace ui #endif // UI_OZONE_PLATFORM_WAYLAND_HOST_WAYLAND_CONNECTION_H_
blueboxd/chromium-legacy
ui/accessibility/platform/ax_platform_node_auralinux.h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_AURALINUX_H_ #define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_AURALINUX_H_ #include <atk/atk.h> #include <memory> #include <string> #include <utility> #include "base/macros.h" #include "base/strings/utf_offset_string_conversions.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/accessibility/ax_enums.mojom-forward.h" #include "ui/accessibility/ax_export.h" #include "ui/accessibility/platform/ax_platform_node_base.h" // This deleter is used in order to ensure that we properly always free memory // used by AtkAttributeSet. struct AtkAttributeSetDeleter { void operator()(AtkAttributeSet* attributes) { atk_attribute_set_free(attributes); } }; using AtkAttributes = std::unique_ptr<AtkAttributeSet, AtkAttributeSetDeleter>; // Some ATK interfaces require returning a (const gchar*), use // this macro to make it safe to return a pointer to a temporary // string. #define ATK_AURALINUX_RETURN_STRING(str_expr) \ { \ static std::string result; \ result = (str_expr); \ return result.c_str(); \ } namespace ui { struct FindInPageResultInfo { AtkObject* node; int start_offset; int end_offset; bool operator==(const FindInPageResultInfo& other) const { return (node == other.node) && (start_offset == other.start_offset) && (end_offset == other.end_offset); } }; // AtkTableCell was introduced in ATK 2.12. Ubuntu Trusty has ATK 2.10. // Compile-time checks are in place for ATK versions that are older than 2.12. // However, we also need runtime checks in case the version we are building // against is newer than the runtime version. To prevent a runtime error, we // check that we have a version of ATK that supports AtkTableCell. If we do, // we dynamically load the symbol; if we don't, the interface is absent from // the accessible object and its methods will not be exposed or callable. // The definitions below ensure we have no missing symbols. Note that in // environments where we have ATK > 2.12, the definitions of AtkTableCell and // AtkTableCellIface below are overridden by the runtime version. // TODO(accessibility) Remove AtkTableCellInterface when 2.12 is the minimum // supported version. struct AX_EXPORT AtkTableCellInterface { typedef struct _AtkTableCell AtkTableCell; static GType GetType(); static GPtrArray* GetColumnHeaderCells(AtkTableCell* cell); static GPtrArray* GetRowHeaderCells(AtkTableCell* cell); static bool GetRowColumnSpan(AtkTableCell* cell, gint* row, gint* column, gint* row_span, gint* col_span); static bool Exists(); }; // This class with an enum is used to generate a bitmask which tracks the ATK // interfaces that an AXPlatformNodeAuraLinux's ATKObject implements. class ImplementedAtkInterfaces { public: enum class Value { kDefault = 1 << 1, kDocument = 1 << 1, kHyperlink = 1 << 2, kHypertext = 1 << 3, kImage = 1 << 4, kSelection = 1 << 5, kTableCell = 1 << 6, kTable = 1 << 7, kText = 1 << 8, kValue = 1 << 9, kWindow = 1 << 10, }; bool Implements(Value interface) const { return value_ & static_cast<int>(interface); } void Add(Value other) { value_ |= static_cast<int>(other); } bool operator!=(const ImplementedAtkInterfaces& other) { return value_ != other.value_; } int value() const { return value_; } private: int value_ = static_cast<int>(Value::kDefault); }; // Implements accessibility on Aura Linux using ATK. class AX_EXPORT AXPlatformNodeAuraLinux : public AXPlatformNodeBase { public: AXPlatformNodeAuraLinux(); ~AXPlatformNodeAuraLinux() override; AXPlatformNodeAuraLinux(const AXPlatformNodeAuraLinux&) = delete; AXPlatformNodeAuraLinux& operator=(const AXPlatformNodeAuraLinux&) = delete; static AXPlatformNodeAuraLinux* FromAtkObject(const AtkObject*); // Set or get the root-level Application object that's the parent of all // top-level windows. static void SetApplication(AXPlatformNode* application); static AXPlatformNode* application(); static void EnsureGTypeInit(); // Do asynchronous static initialization. static void StaticInitialize(); // Enables AXMode calling AXPlatformNode::NotifyAddAXModeFlags. It's used // when ATK APIs are called. static void EnableAXMode(); // EnsureAtkObjectIsValid will destroy and recreate |atk_object_| if the // interface mask is different. This partially relies on looking at the tree's // structure. This must not be called when the tree is unstable e.g. in the // middle of being unserialized. void EnsureAtkObjectIsValid(); void Destroy() override; AtkRole GetAtkRole() const; void GetAtkState(AtkStateSet* state_set); AtkRelationSet* GetAtkRelations(); void GetExtents(gint* x, gint* y, gint* width, gint* height, AtkCoordType coord_type); void GetPosition(gint* x, gint* y, AtkCoordType coord_type); void GetSize(gint* width, gint* height); gfx::NativeViewAccessible HitTestSync(gint x, gint y, AtkCoordType coord_type); bool GrabFocus(); bool FocusFirstFocusableAncestorInWebContent(); bool GrabFocusOrSetSequentialFocusNavigationStartingPointAtOffset(int offset); bool GrabFocusOrSetSequentialFocusNavigationStartingPoint(); bool SetSequentialFocusNavigationStartingPoint(); bool DoDefaultAction(); const gchar* GetDefaultActionName(); AtkAttributeSet* GetAtkAttributes(); gfx::Vector2d GetParentOriginInScreenCoordinates() const; gfx::Vector2d GetParentFrameOriginInScreenCoordinates() const; gfx::Rect GetExtentsRelativeToAtkCoordinateType( AtkCoordType coord_type) const; // AtkDocument helpers const gchar* GetDocumentAttributeValue(const gchar* attribute) const; AtkAttributeSet* GetDocumentAttributes() const; // AtkHyperlink helpers AtkHyperlink* GetAtkHyperlink(); #if defined(ATK_CHECK_VERSION) && ATK_CHECK_VERSION(2, 30, 0) void ScrollToPoint(AtkCoordType atk_coord_type, int x, int y); void ScrollNodeRectIntoView(gfx::Rect rect, AtkScrollType atk_scroll_type); void ScrollNodeIntoView(AtkScrollType atk_scroll_type); #endif // defined(ATK_CHECK_VERSION) && ATK_CHECK_VERSION(2, 30, 0) #if defined(ATK_CHECK_VERSION) && ATK_CHECK_VERSION(2, 32, 0) absl::optional<gfx::Rect> GetUnclippedHypertextRangeBoundsRect( int start_offset, int end_offset); bool ScrollSubstringIntoView(AtkScrollType atk_scroll_type, int start_offset, int end_offset); bool ScrollSubstringToPoint(int start_offset, int end_offset, AtkCoordType atk_coord_type, int x, int y); #endif // defined(ATK_CHECK_VERSION) && ATK_CHECK_VERSION(2, 32, 0) // Misc helpers void GetFloatAttributeInGValue(ax::mojom::FloatAttribute attr, GValue* value); // Event helpers void OnActiveDescendantChanged(); void OnCheckedStateChanged(); void OnEnabledChanged(); void OnExpandedStateChanged(bool is_expanded); void OnShowingStateChanged(bool is_showing); void OnFocused(); void OnWindowActivated(); void OnWindowDeactivated(); void OnMenuPopupStart(); void OnMenuPopupEnd(); void OnAllMenusEnded(); void OnSelected(); void OnSelectedChildrenChanged(); void OnTextAttributesChanged(); void OnTextSelectionChanged(); void OnValueChanged(); void OnNameChanged(); void OnDescriptionChanged(); void OnSortDirectionChanged(); void OnInvalidStatusChanged(); void OnAriaCurrentChanged(); void OnDocumentTitleChanged(); void OnSubtreeCreated(); void OnSubtreeWillBeDeleted(); void OnParentChanged(); void OnReadonlyChanged(); void OnWindowVisibilityChanged(); void OnScrolledToAnchor(); void OnAlertShown(); void RunPostponedEvents(); void ResendFocusSignalsForCurrentlyFocusedNode(); bool SupportsSelectionWithAtkSelection(); bool SelectionAndFocusAreTheSame(); void SetActiveViewsDialog(); // AXPlatformNode overrides. // This has a side effect of creating the AtkObject if one does not already // exist. gfx::NativeViewAccessible GetNativeViewAccessible() override; void NotifyAccessibilityEvent(ax::mojom::Event event_type) override; // AXPlatformNodeBase overrides. void Init(AXPlatformNodeDelegate* delegate) override; bool IsPlatformCheckable() const override; absl::optional<int> GetIndexInParent() override; bool IsNameExposed(); void UpdateHypertext(); const AXLegacyHypertext& GetAXHypertext(); const base::OffsetAdjuster::Adjustments& GetHypertextAdjustments(); size_t UTF16ToUnicodeOffsetInText(size_t utf16_offset); size_t UnicodeToUTF16OffsetInText(int unicode_offset); int GetTextOffsetAtPoint(int x, int y, AtkCoordType atk_coord_type); // Called on a toplevel frame to set the document parent, which is the parent // of the toplevel document. This is used to properly express the ATK embeds // relationship between a toplevel frame and its embedded document. void SetDocumentParent(AtkObject* new_document_parent); int GetCaretOffset(); bool SetCaretOffset(int offset); bool SetTextSelectionForAtkText(int start_offset, int end_offset); bool HasSelection(); void GetSelectionExtents(int* start_offset, int* end_offset); gchar* GetSelectionWithText(int* start_offset, int* end_offset); // Return the text attributes for this node given an offset. The start // and end attributes will be assigned to the start_offset and end_offset // pointers if they are non-null. The return value AtkAttributeSet should // be freed with atk_attribute_set_free. const TextAttributeList& GetTextAttributes(int offset, int* start_offset, int* end_offset); // Return the default text attributes for this node. The default text // attributes are the ones that apply to the entire node. Attributes found at // a given offset can be thought of as overriding the default attribute. // The return value AtkAttributeSet should be freed with // atk_attribute_set_free. const TextAttributeList& GetDefaultTextAttributes(); void ActivateFindInPageResult(int start_offset, int end_offset); void TerminateFindInPage(); // If there is a find in page result for the toplevel document of this node, // return it, otherwise return absl::nullopt; absl::optional<FindInPageResultInfo> GetSelectionOffsetsFromFindInPage(); std::pair<int, int> GetSelectionOffsetsForAtk(); // Get the embedded object ("hyperlink") indices for this object in the // parent. If this object doesn't have a parent or isn't embedded, return // nullopt. absl::optional<std::pair<int, int>> GetEmbeddedObjectIndices(); std::vector<ax::mojom::Action> GetSupportedActions() const; bool HasDefaultActionVerb() const; std::string accessible_name_; protected: // Offsets for the AtkText API are calculated in UTF-16 code point offsets, // but the ATK APIs want all offsets to be in "characters," which we // understand to be Unicode character offsets. We keep a lazily generated set // of Adjustments to convert between UTF-16 and Unicode character offsets. absl::optional<base::OffsetAdjuster::Adjustments> text_unicode_adjustments_ = absl::nullopt; void AddAttributeToList(const char* name, const char* value, PlatformAttributeList* attributes) override; private: // This is static to ensure that we aren't trying to access the rest of the // accessibility tree during node initialization. static ImplementedAtkInterfaces GetGTypeInterfaceMask(const AXNodeData& data); GType GetAccessibilityGType(); AtkObject* CreateAtkObject(); // Get or Create AtkObject. Note that it could return nullptr except // ax::mojom::Role::kApplication when the mode is not enabled. gfx::NativeViewAccessible GetOrCreateAtkObject(); void DestroyAtkObjects(); void AddRelationToSet(AtkRelationSet*, AtkRelationType, AXPlatformNode* target); bool IsInLiveRegion(); absl::optional<std::pair<int, int>> GetEmbeddedObjectIndicesForId(int id); void ComputeStylesIfNeeded(); int FindStartOfStyle(int start_offset, ax::mojom::MoveDirection direction); // Reset any find in page operations for the toplevel document of this node. void ForgetCurrentFindInPageResult(); // Activate a find in page result for the toplevel document of this node. void ActivateFindInPageInParent(int start_offset, int end_offset); // If this node is the toplevel document node, find its parent and set it on // the toplevel frame which contains the node. void SetDocumentParentOnFrameIfNecessary(); // Find the child which is a document containing the primary web content. AtkObject* FindPrimaryWebContentDocument(); // Returns true if it is a web content for the relations. bool IsWebDocumentForRelations(); // If a selection that intersects this node get the full selection // including start and end node ids. void GetFullSelection(int32_t* anchor_node_id, int* anchor_offset, int32_t* focus_node_id, int* focus_offset); // Returns true if this node's AtkObject is suitable for emitting AtkText // signals. ATs don't expect static text objects to emit AtkText signals. bool EmitsAtkTextEvents() const; // Find the first ancestor which is an editable root or a document. This node // will be one which contains a single selection. AXPlatformNodeAuraLinux& FindEditableRootOrDocument(); // Find the first common ancestor between this node and a given node. AXPlatformNodeAuraLinux* FindCommonAncestor(AXPlatformNodeAuraLinux* other); // Update the selection information stored in this node. This should be // called on the editable root, the root node of the accessibility tree, or // the document (ie the node returned by FindEditableRootOrDocument()). void UpdateSelectionInformation(int32_t anchor_node_id, int anchor_offset, int32_t focus_node_id, int focus_offset); // Emit a GObject signal indicating a selection change. void EmitSelectionChangedSignal(bool had_selection); // Emit a GObject signal indicating that the caret has moved. void EmitCaretChangedSignal(); bool HadNonZeroWidthSelection() const { return had_nonzero_width_selection; } std::pair<int32_t, int> GetCurrentCaret() const { return current_caret_; } // If the given argument can be found as a child of this node, return its // hypertext extents, otherwise return absl::nullopt; absl::optional<std::pair<int, int>> GetHypertextExtentsOfChild( AXPlatformNodeAuraLinux* child); // The AtkStateType for a checkable node can vary depending on the role. AtkStateType GetAtkStateTypeForCheckableNode(); gfx::Point ConvertPointToScreenCoordinates(const gfx::Point& point, AtkCoordType atk_coord_type); // Keep information of latest ImplementedAtkInterfaces mask to rebuild the // ATK object accordingly when the platform node changes. ImplementedAtkInterfaces interface_mask_; // We own a reference to these ref-counted objects. AtkObject* atk_object_ = nullptr; AtkHyperlink* atk_hyperlink_ = nullptr; // A weak pointers which help us track the ATK embeds relation. AtkObject* document_parent_ = nullptr; // Whether or not this node (if it is a frame or a window) was // minimized the last time it's visibility changed. bool was_minimized_ = false; // Information about the selection meant to be stored on the return value of // FindEditableRootOrDocument(). // // Whether or not we previously had a selection where the anchor and focus // were not equal. This is what ATK consider a "selection." bool had_nonzero_width_selection = false; // Information about the current caret location (a node id and an offset). // This is used to track when the caret actually moves during a selection // change. std::pair<int32_t, int> current_caret_ = {-1, -1}; // A map which converts between an offset in the node's hypertext and the // ATK text attributes at that offset. TextAttributeMap offset_to_text_attributes_; // The default ATK text attributes for this node. TextAttributeList default_text_attributes_; bool window_activate_event_postponed_ = false; }; } // namespace ui #endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_AURALINUX_H_
blueboxd/chromium-legacy
chrome/browser/chromeos/policy/dlp/dlp_content_observer.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_POLICY_DLP_DLP_CONTENT_OBSERVER_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_DLP_DLP_CONTENT_OBSERVER_H_ #include "chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.h" class GURL; namespace content { class WebContents; } // namespace content namespace policy { // Interface for a class observing changed in Data Leak Prevention restricted // content per WebContents object. class DlpContentObserver { public: // Returns proper implementation of the interface. Never returns nullptr. static DlpContentObserver* Get(); virtual ~DlpContentObserver() = default; // Being called when confidentiality state changes for |web_contents|, e.g. // because of navigation. virtual void OnConfidentialityChanged( content::WebContents* web_contents, const DlpContentRestrictionSet& restriction_set) = 0; // Called when |web_contents| is about to be destroyed. virtual void OnWebContentsDestroyed(content::WebContents* web_contents) = 0; // Returns which content restrictions are being applied to the |url| according // to the policies. virtual DlpContentRestrictionSet GetRestrictionSetForURL( const GURL& url) const; // Called when |web_contents| becomes visible or not. virtual void OnVisibilityChanged(content::WebContents* web_contents) = 0; private: friend class ScopedDlpContentObserverForTesting; static void SetDlpContentObserverForTesting( DlpContentObserver* dlp_content_observer); static void ResetDlpContentObserverForTesting(); }; // Helper class to call SetDlpContentObserverForTesting and // ResetDlpContentObserverForTesting automatically. // The caller (test) should manage `test_dlp_content_observer` lifetime. // This class does not own it. class ScopedDlpContentObserverForTesting { public: explicit ScopedDlpContentObserverForTesting( DlpContentObserver* test_dlp_content_observer); ~ScopedDlpContentObserverForTesting(); }; } // namespace policy #endif // CHROME_BROWSER_CHROMEOS_POLICY_DLP_DLP_CONTENT_OBSERVER_H_
blueboxd/chromium-legacy
components/sync/test/fake_server/bookmark_entity_builder.h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SYNC_TEST_FAKE_SERVER_BOOKMARK_ENTITY_BUILDER_H_ #define COMPONENTS_SYNC_TEST_FAKE_SERVER_BOOKMARK_ENTITY_BUILDER_H_ #include <memory> #include <string> #include "base/guid.h" #include "components/sync/base/model_type.h" #include "components/sync/engine/loopback_server/loopback_server_entity.h" #include "components/sync/protocol/unique_position.pb.h" #include "ui/gfx/image/image.h" #include "url/gurl.h" namespace sync_pb { class BookmarkSpecifics; class EntitySpecifics; } // namespace sync_pb namespace fake_server { // Builder for BookmarkEntity objects. class BookmarkEntityBuilder { public: // Represents different generations of bookmarks ordered by time. It doesn't // contain all generations and may reflect differences in specifics and // SyncEntity. enum class BookmarkGeneration { // A bookmark which doesn't contain title and GUID in specifics. kWithoutTitleInSpecifics, // A bookmark entity having legacy title in specifics and uppercase GUID in // |originator_client_item_id| // without GUID in specifics. For bookmarks created between M45 and M51. kLegacyTitleUppercaseOriginatorClientItemId, // A bookmark which contains valid GUID in specifics and // |originator_client_item_id|. For bookmarks created after M52. kLegacyTitleWithoutGuidInSpecifics, // Contains legacy title and GUID in specifics which matches to // |originator_client_item_id| (see BookmarkSpecifics for details). // Introduced in M81. kValidGuidAndLegacyTitle, // Contains both legacy title and full title in specifics. Introduced in // M83. kValidGuidAndFullTitle, // Contains |unique_position|, |type| and |parent_guid| in specifics. // Introduced in M94. kHierarchyFieldsInSpecifics, }; BookmarkEntityBuilder(const std::string& title, const std::string& originator_cache_guid, const std::string& originator_client_item_id); BookmarkEntityBuilder(const BookmarkEntityBuilder& other); ~BookmarkEntityBuilder(); // Sets the ID for the bookmark to be built. The ID should be in the format // returned by LoopbackServerEntity::CreateId. If this is not called, a random // ID will be generated. void SetId(const std::string& id); // Sets the parent ID of the bookmark to be built. If this is not called, // the bookmark will be included in the bookmarks bar. BookmarkEntityBuilder& SetParentId(const std::string& parent_id); // Set parent GUID to populate in specifics for generations above // |kHierarchyFieldsInSpecifics|. The GUID must be valid. BookmarkEntityBuilder& SetParentGuid(const base::GUID& parent_guid); // Sets the index of the bookmark to be built. If this is not called, // the bookmark will be placed at index 0. void SetIndex(int index); // Update bookmark's generation, will be used to fill in the final entity // fields. BookmarkEntityBuilder& SetGeneration(BookmarkGeneration generation); BookmarkEntityBuilder& SetFavicon(const gfx::Image& favicon, const GURL& icon_url); // Builds and returns a LoopbackServerEntity representing a bookmark. Returns // null if the entity could not be built. std::unique_ptr<syncer::LoopbackServerEntity> BuildBookmark(const GURL& url); // Builds and returns a LoopbackServerEntity representing a bookmark folder. // Returns null if the entity could not be built. std::unique_ptr<syncer::LoopbackServerEntity> BuildFolder(); private: // Creates an EntitySpecifics and pre-populates its BookmarkSpecifics. sync_pb::EntitySpecifics CreateBaseEntitySpecifics(bool is_folder); // Builds the parts of a LoopbackServerEntity common to both normal bookmarks // and folders. std::unique_ptr<syncer::LoopbackServerEntity> Build( const sync_pb::EntitySpecifics& entity_specifics, bool is_folder); // Fill in favicon and icon URL in the specifics. |bookmark_specifics| must // not be nullptr. void FillWithFaviconIfNeeded(sync_pb::BookmarkSpecifics* bookmark_specifics); // Generates unique position based on |index_|, item ID and cache GUID. sync_pb::UniquePosition GenerateUniquePosition() const; // The bookmark entity's title. This value is also used as the entity's name. const std::string title_; // Information that associates the bookmark with its original client. const std::string originator_cache_guid_; const std::string originator_client_item_id_; // The ID for the bookmark. This is only non-empty if it was explicitly set // via SetId(); otherwise a random ID will be generated on demand. std::string id_; // The ID of the parent bookmark folder. std::string parent_id_; base::GUID parent_guid_; // The index of the bookmark folder within its siblings. int index_ = 0; sync_pb::UniquePosition unique_position_; // Information about the favicon of the bookmark. gfx::Image favicon_; GURL icon_url_; // TODO(crbug.com/1063350): update to kHierarchyFieldsInSpecifics. BookmarkGeneration bookmark_generation_ = BookmarkGeneration::kValidGuidAndFullTitle; }; } // namespace fake_server #endif // COMPONENTS_SYNC_TEST_FAKE_SERVER_BOOKMARK_ENTITY_BUILDER_H_
blueboxd/chromium-legacy
content/browser/renderer_host/render_frame_host_android.h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_FRAME_HOST_ANDROID_H_ #define CONTENT_BROWSER_RENDERER_HOST_RENDER_FRAME_HOST_ANDROID_H_ #include <jni.h> #include "base/android/jni_android.h" #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/supports_user_data.h" #include "content/common/content_export.h" namespace content { class RenderFrameHostImpl; // Android wrapper around RenderFrameHost that provides safer passage from java // and back to native and provides java with a means of communicating with its // native counterpart. class RenderFrameHostAndroid : public base::SupportsUserData::Data { public: RenderFrameHostAndroid(RenderFrameHostImpl* render_frame_host); RenderFrameHostAndroid(const RenderFrameHostAndroid&) = delete; RenderFrameHostAndroid& operator=(const RenderFrameHostAndroid&) = delete; ~RenderFrameHostAndroid() override; base::android::ScopedJavaLocalRef<jobject> GetJavaObject(); // Methods called from Java base::android::ScopedJavaLocalRef<jobject> GetLastCommittedURL( JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; base::android::ScopedJavaLocalRef<jobject> GetLastCommittedOrigin( JNIEnv* env, const base::android::JavaParamRef<jobject>&); void GetCanonicalUrlForSharing( JNIEnv* env, const base::android::JavaParamRef<jobject>&, const base::android::JavaParamRef<jobject>& jcallback) const; base::android::ScopedJavaLocalRef<jobjectArray> GetAllRenderFrameHosts( JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; bool IsFeatureEnabled(JNIEnv* env, const base::android::JavaParamRef<jobject>&, jint feature) const; // Returns UnguessableToken. base::android::ScopedJavaLocalRef<jobject> GetAndroidOverlayRoutingToken( JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; void NotifyUserActivation(JNIEnv* env, const base::android::JavaParamRef<jobject>&); jboolean SignalCloseWatcherIfActive( JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; jboolean IsRenderFrameCreated( JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; void GetInterfaceToRendererFrame( JNIEnv* env, const base::android::JavaParamRef<jobject>&, const base::android::JavaParamRef<jstring>& interface_name, jint message_pipe_handle) const; void TerminateRendererDueToBadMessage( JNIEnv* env, const base::android::JavaParamRef<jobject>&, jint reason) const; jboolean IsProcessBlocked(JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; base::android::ScopedJavaLocalRef<jobject> PerformGetAssertionWebAuthSecurityChecks( JNIEnv* env, const base::android::JavaParamRef<jobject>&, const base::android::JavaParamRef<jstring>&, const base::android::JavaParamRef<jobject>&, jboolean is_payment_credential_get_assertion) const; jint PerformMakeCredentialWebAuthSecurityChecks( JNIEnv* env, const base::android::JavaParamRef<jobject>&, const base::android::JavaParamRef<jstring>&, const base::android::JavaParamRef<jobject>&, jboolean is_payment_credential_creation) const; jint GetLifecycleState(JNIEnv* env, const base::android::JavaParamRef<jobject>&) const; RenderFrameHostImpl* render_frame_host() const { return render_frame_host_; } private: RenderFrameHostImpl* const render_frame_host_; JavaObjectWeakGlobalRef obj_; }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_FRAME_HOST_ANDROID_H_
blueboxd/chromium-legacy
device/bluetooth/floss/floss_adapter_client.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DEVICE_BLUETOOTH_FLOSS_FLOSS_ADAPTER_CLIENT_H_ #define DEVICE_BLUETOOTH_FLOSS_FLOSS_ADAPTER_CLIENT_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "dbus/exported_object.h" #include "dbus/object_path.h" #include "device/bluetooth/bluetooth_export.h" #include "device/bluetooth/floss/floss_dbus_client.h" namespace dbus { class ErrorResponse; class MessageReader; class MessageWriter; class ObjectPath; class Response; } // namespace dbus namespace floss { // The adapter client represents a specific adapter and exposes some common // functionality on it (such as discovery and bonding). It is managed by // FlossClientBundle and will be initialized only when the chosen adapter is // powered on (presence and power management is done by |FlossManagerClient|). class DEVICE_BLUETOOTH_EXPORT FlossAdapterClient : public FlossDBusClient { public: enum class BluetoothTransport { kAuto = 0, kBrEdr = 1, kLe = 2, }; enum class BluetoothSspVariant { kPasskeyConfirmation = 0, kPasskeyEntry = 1, kConsent = 2, kPasskeyNotification = 3, }; enum class BondState { kNotBonded = 0, kBondingInProgress = 1, kBonded = 2, }; class Observer : public base::CheckedObserver { public: Observer(const Observer&) = delete; Observer& operator=(const Observer&) = delete; Observer() = default; ~Observer() override = default; // Notification sent when the adapter address has changed. virtual void AdapterAddressChanged(const std::string& address) {} // Notification sent when the discovering state has changed. virtual void AdapterDiscoveringChanged(bool state) {} // Notification sent when discovery has found a device. This notification // is not guaranteed to be unique per Chrome discovery session (i.e. you can // get the same device twice). virtual void AdapterFoundDevice(const FlossDeviceId& device_found) {} // Notification sent for Simple Secure Pairing. virtual void AdapterSspRequest(const FlossDeviceId& remote_device, uint32_t cod, BluetoothSspVariant variant, uint32_t passkey) {} // Notification sent when a bonding state changes for a remote device. // TODO(b:202334519): Change status type to enum once Floss has the enum. virtual void DeviceBondStateChanged(const FlossDeviceId& remote_device, uint32_t status, BondState bond_state) {} }; // Error: No such adapter. static const char kErrorUnknownAdapter[]; // Creates the instance. static std::unique_ptr<FlossAdapterClient> Create(); // Parses |FlossDeviceId| from a property map in DBus. The data is provided as // an array of dict entries (with a signature of a{sv}). static bool ParseFlossDeviceId(dbus::MessageReader* reader, FlossDeviceId* device); // Serializes |FlossDeviceId| as a property map in DBus (written as an array // of dict entries with a signature of a{sv}). static void SerializeFlossDeviceId(dbus::MessageWriter* writer, const FlossDeviceId& device); FlossAdapterClient(const FlossAdapterClient&) = delete; FlossAdapterClient& operator=(const FlossAdapterClient&) = delete; FlossAdapterClient(); ~FlossAdapterClient() override; // Manage observers. void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); // Get the address of this adapter. const std::string& GetAddress() const { return adapter_address_; } // Start a discovery session. virtual void StartDiscovery(ResponseCallback callback); // Cancel the active discovery session. virtual void CancelDiscovery(ResponseCallback callback); // Create a bond with the given device and transport. virtual void CreateBond(ResponseCallback callback, FlossDeviceId device, BluetoothTransport transport); // Get the object path for this adapter. const dbus::ObjectPath* GetObjectPath() const { return &adapter_path_; } // Initialize the adapter client. void Init(dbus::Bus* bus, const std::string& service_name, const std::string& adapter_path) override; protected: friend class FlossAdapterClientTest; // Handle response to |GetAddress| DBus method call. void HandleGetAddress(dbus::Response* response, dbus::ErrorResponse* error_response); // Handle callback |OnAddressChanged| on exported object path. void OnAddressChanged(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender); // Handle callback |OnDiscoveringChanged| on exported object path. void OnDiscoveringChanged( dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender); // Handle callback |OnDeviceFound| on exported object path. void OnDeviceFound(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender); // Handle callback |OnSspRequest| on exported object path. void OnSspRequest(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender); // Handle callback |OnBondStateChanged| on exported object path. void OnBondStateChanged(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender); // List of observers interested in event notifications from this client. base::ObserverList<Observer> observers_; // Managed by FlossDBusManager - we keep local pointer to access object proxy. dbus::Bus* bus_ = nullptr; // Adapter managed by this client. dbus::ObjectPath adapter_path_; // Service which implements the adapter interface. std::string service_name_; // Address of adapter. std::string adapter_address_; private: // Object path for exported callbacks registered against adapter interface. static const char kExportedCallbacksPath[]; base::WeakPtrFactory<FlossAdapterClient> weak_ptr_factory_{this}; }; } // namespace floss #endif // DEVICE_BLUETOOTH_FLOSS_FLOSS_ADAPTER_CLIENT_H_
blueboxd/chromium-legacy
components/safe_browsing/content/browser/triggers/suspicious_site_trigger.h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SAFE_BROWSING_CONTENT_BROWSER_TRIGGERS_SUSPICIOUS_SITE_TRIGGER_H_ #define COMPONENTS_SAFE_BROWSING_CONTENT_BROWSER_TRIGGERS_SUSPICIOUS_SITE_TRIGGER_H_ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" class PrefService; namespace history { class HistoryService; } namespace network { class SharedURLLoaderFactory; } // namespace network namespace safe_browsing { class ReferrerChainProvider; class TriggerManager; // Metric for tracking what the Suspicious Site trigger does on each event. extern const char kSuspiciousSiteTriggerEventMetricName[]; // Metric for tracking how often reports from this trigger are rejected by the // trigger manager, and for what reason. extern const char kSuspiciousSiteTriggerReportRejectionMetricName[]; // Local metric for tracking the state of the trigger when the report delay // timer fires. extern const char kSuspiciousSiteTriggerReportDelayStateTestMetricName[]; // Tracks events this trigger listens for or actions it performs. These values // are written to logs. New enum values can be added, but existing enums must // never be renumbered or deleted and reused. enum class SuspiciousSiteTriggerEvent { // A page load started. PAGE_LOAD_START = 0, // A page load finished. PAGE_LOAD_FINISH = 1, // A suspicious site was detected. SUSPICIOUS_SITE_DETECTED = 2, // The report delay timer fired. REPORT_DELAY_TIMER = 3, // A suspicious site report was started. REPORT_STARTED = 4, // A suspicious site report was created and sent. REPORT_FINISHED = 5, // The trigger was waiting for a load to finish before creating a report but // a new load started before the previous load could finish, so the report // was cancelled. PENDING_REPORT_CANCELLED_BY_LOAD = 6, // The trigger tried to start the report but it was rejected by the trigger // manager. REPORT_START_FAILED = 7, // The trigger tried to finish the report but it was rejected by the trigger // manager. REPORT_FINISH_FAILED = 8, // The trigger could have sent a report but it was skipped, typically because // the trigger was out of quota. REPORT_POSSIBLE_BUT_SKIPPED = 9, // New events must be added before kMaxValue, and the value of kMaxValue // updated. kMaxValue = REPORT_POSSIBLE_BUT_SKIPPED }; // Notify a suspicious site trigger on a particular tab that a suspicious site // was detected. |web_contents_getter| specifies the tab where the site was // detected. // Must be called on UI thread. void NotifySuspiciousSiteTriggerDetected( const base::RepeatingCallback<content::WebContents*()>& web_contents_getter); // This class watches tab-level events such as the start and end of a page // load, and also listens for events from the SuspiciousSiteURLThrottle that // indicate there was a hit on the suspicious site list. This trigger is // repsonsible for creating reports about the page at the right time, based on // the sequence of such events. class SuspiciousSiteTrigger : public content::WebContentsObserver, public content::WebContentsUserData<SuspiciousSiteTrigger> { public: // The different states the trigger could be in. // These values are written to logs. New enum values can be added, but // existing enums must never be renumbered or deleted and reused. enum class TriggerState { // Trigger is idle, page is not loading, no report requested. IDLE = 0, // Page load has started, no report requested. LOADING = 1, // Page load has started and a report is requested. The report will be // created when the page load finishes. LOADING_WILL_REPORT = 2, // A page load finished and a report for the page has started. REPORT_STARTED = 3, // The trigger is in monitoring mode where it listens for events and // increments some metrics but never sends reports. The trigger will never // leave this state. MONITOR_MODE = 4, // New states must be added before kMaxValue and the value of kMaxValue // updated. kMaxValue = MONITOR_MODE }; SuspiciousSiteTrigger(const SuspiciousSiteTrigger&) = delete; SuspiciousSiteTrigger& operator=(const SuspiciousSiteTrigger&) = delete; ~SuspiciousSiteTrigger() override; // content::WebContentsObserver implementations. void DidStartLoading() override; void DidStopLoading() override; // Called when a suspicious site has been detected on the tab that this // trigger is running on. void SuspiciousSiteDetected(); private: friend class content::WebContentsUserData<SuspiciousSiteTrigger>; friend class SuspiciousSiteTriggerTest; SuspiciousSiteTrigger( content::WebContents* web_contents, TriggerManager* trigger_manager, PrefService* prefs, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, history::HistoryService* history_service, ReferrerChainProvider* referrer_chain_provider, bool monitor_mode); // Tries to start a report. Returns whether a report started successfully. // If a report is started, a delayed callback will also begin to notify // the trigger when the report should be completed and sent. bool MaybeStartReport(); // Calls into the trigger manager to finish the active report and send it. void FinishReport(); // Called when a suspicious site is detected while in monitor mode. We update // metrics if we determine that a report could have been sent had the trigger // been active. void SuspiciousSiteDetectedWhenMonitoring(); // Called when the report delay timer fires, indicating that the active // report should be completed and sent. void ReportDelayTimerFired(); // Sets a task runner to use for tests. void SetTaskRunnerForTest( scoped_refptr<base::SequencedTaskRunner> task_runner); // The delay (in milliseconds) to wait before finishing a report. Can be // overwritten for tests. int64_t finish_report_delay_ms_; // Current state of the trigger. Used to synchronize page load events with // suspicious site list hit events so that reports can be generated at the // right time. TriggerState current_state_; // TriggerManager gets called if this trigger detects a suspicious site and // wants to collect data abou tit. Not owned. TriggerManager* trigger_manager_; PrefService* prefs_; scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; history::HistoryService* history_service_; ReferrerChainProvider* referrer_chain_provider_; // Task runner for posting delayed tasks. Normally set to the runner for the // UI thread, but can be overwritten for tests. scoped_refptr<base::SequencedTaskRunner> task_runner_; base::WeakPtrFactory<SuspiciousSiteTrigger> weak_ptr_factory_{this}; WEB_CONTENTS_USER_DATA_KEY_DECL(); }; } // namespace safe_browsing #endif // COMPONENTS_SAFE_BROWSING_CONTENT_BROWSER_TRIGGERS_SUSPICIOUS_SITE_TRIGGER_H_
blueboxd/chromium-legacy
ash/app_list/test/app_list_test_helper.h
<reponame>blueboxd/chromium-legacy<filename>ash/app_list/test/app_list_test_helper.h // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_APP_LIST_TEST_APP_LIST_TEST_HELPER_H_ #define ASH_APP_LIST_TEST_APP_LIST_TEST_HELPER_H_ #include <memory> #include "ash/app_list/app_list_metrics.h" #include "ash/app_list/model/search/search_model.h" #include "ash/app_list/test_app_list_client.h" namespace ash { class AppListBubbleAppsPage; class AppListBubbleAssistantPage; class AppListBubbleSearchPage; class AppListBubbleView; class AppListControllerImpl; class AppListFolderView; class AppListView; class AppsContainerView; class ContinueSectionView; class PagedAppsGridView; class RecentAppsView; class ScrollableAppsGridView; class SearchBoxView; enum class AppListViewState; class AppListTestHelper { public: AppListTestHelper(); AppListTestHelper(const AppListTestHelper&) = delete; AppListTestHelper& operator=(const AppListTestHelper&) = delete; ~AppListTestHelper(); // Shows the app list on the default display. void ShowAppList(); // Show the app list in |display_id|, and wait until animation finishes. // Note: we usually don't care about the show source in tests. void ShowAndRunLoop(uint64_t display_id); // Show the app list in |display_id|. void Show(uint64_t display_id); // Show the app list in |display_id| triggered with |show_source|, and wait // until animation finishes. void ShowAndRunLoop(uint64_t display_id, AppListShowSource show_source); // Dismiss the app list, and wait until animation finishes. void DismissAndRunLoop(); // Dismiss the app list. void Dismiss(); // Toggle the app list in |display_id|, and wait until animation finishes. // Note: we usually don't care about the show source in tests. void ToggleAndRunLoop(uint64_t display_id); // Toggle the app list in |display_id| triggered with |show_source|, and wait // until animation finishes. void ToggleAndRunLoop(uint64_t display_id, AppListShowSource show_source); // Check the visibility value of the app list and its target. // Fails in tests if either one doesn't match |visible|. // DEPRECATED: Prefer to EXPECT_TRUE or EXPECT_FALSE the visibility directly, // so a failing test will print the line number of the expectation that // failed. void CheckVisibility(bool visible); // Check the current app list view state. void CheckState(AppListViewState state); // Run all pending in message loop to wait for animation to finish. void WaitUntilIdle(); // Adds `num_apps` to the app list model. void AddAppItems(int num_apps); // Adds a page break item to the app list model. void AddPageBreakItem(); // Adds `num_apps` recent apps to the recent apps view. void AddRecentApps(int num_apps); // Whether the app list is showing a folder. bool IsInFolderView(); // Fullscreen/peeking launcher helpers. AppListView* GetAppListView(); AppsContainerView* GetAppsContainerView(); AppListFolderView* GetFullscreenFolderView(); RecentAppsView* GetFullscreenRecentAppsView(); // Paged launcher helpers. PagedAppsGridView* GetRootPagedAppsGridView(); // Bubble launcher helpers. The bubble must be open before calling these. AppListBubbleView* GetBubbleView(); SearchBoxView* GetBubbleSearchBoxView(); AppListFolderView* GetBubbleFolderView(); AppListBubbleAppsPage* GetBubbleAppsPage(); ContinueSectionView* GetContinueSectionView(); RecentAppsView* GetBubbleRecentAppsView(); ScrollableAppsGridView* GetScrollableAppsGridView(); AppListBubbleSearchPage* GetBubbleSearchPage(); AppListBubbleAssistantPage* GetBubbleAssistantPage(); SearchModel::SearchResults* GetSearchResults(); TestAppListClient* app_list_client() { return app_list_client_.get(); } private: AppListControllerImpl* app_list_controller_ = nullptr; std::unique_ptr<TestAppListClient> app_list_client_; }; } // namespace ash #endif // ASH_APP_LIST_TEST_APP_LIST_TEST_HELPER_H_
blueboxd/chromium-legacy
media/mojo/mojom/stable/stable_video_decoder_types_mojom_traits.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_MOJO_MOJOM_STABLE_STABLE_VIDEO_DECODER_TYPES_MOJOM_TRAITS_H_ #define MEDIA_MOJO_MOJOM_STABLE_STABLE_VIDEO_DECODER_TYPES_MOJOM_TRAITS_H_ #include "media/mojo/mojom/stable/stable_video_decoder_types.mojom.h" namespace mojo { template <> struct EnumTraits<media::stable::mojom::ColorSpacePrimaryID, gfx::ColorSpace::PrimaryID> { static media::stable::mojom::ColorSpacePrimaryID ToMojom( gfx::ColorSpace::PrimaryID input) { switch (input) { case gfx::ColorSpace::PrimaryID::INVALID: return media::stable::mojom::ColorSpacePrimaryID::kInvalid; case gfx::ColorSpace::PrimaryID::BT709: return media::stable::mojom::ColorSpacePrimaryID::kBT709; case gfx::ColorSpace::PrimaryID::BT470M: return media::stable::mojom::ColorSpacePrimaryID::kBT470M; case gfx::ColorSpace::PrimaryID::BT470BG: return media::stable::mojom::ColorSpacePrimaryID::kBT470BG; case gfx::ColorSpace::PrimaryID::SMPTE170M: return media::stable::mojom::ColorSpacePrimaryID::kSMPTE170M; case gfx::ColorSpace::PrimaryID::SMPTE240M: return media::stable::mojom::ColorSpacePrimaryID::kSMPTE240M; case gfx::ColorSpace::PrimaryID::FILM: return media::stable::mojom::ColorSpacePrimaryID::kFilm; case gfx::ColorSpace::PrimaryID::BT2020: return media::stable::mojom::ColorSpacePrimaryID::kBT2020; case gfx::ColorSpace::PrimaryID::SMPTEST428_1: return media::stable::mojom::ColorSpacePrimaryID::kSMPTEST428_1; case gfx::ColorSpace::PrimaryID::SMPTEST431_2: return media::stable::mojom::ColorSpacePrimaryID::kSMPTEST431_2; case gfx::ColorSpace::PrimaryID::SMPTEST432_1: return media::stable::mojom::ColorSpacePrimaryID::kSMPTEST432_1; case gfx::ColorSpace::PrimaryID::XYZ_D50: return media::stable::mojom::ColorSpacePrimaryID::kXYZ_D50; case gfx::ColorSpace::PrimaryID::ADOBE_RGB: return media::stable::mojom::ColorSpacePrimaryID::kAdobeRGB; case gfx::ColorSpace::PrimaryID::APPLE_GENERIC_RGB: return media::stable::mojom::ColorSpacePrimaryID::kAppleGenericRGB; case gfx::ColorSpace::PrimaryID::WIDE_GAMUT_COLOR_SPIN: return media::stable::mojom::ColorSpacePrimaryID::kWideGamutColorSpin; case gfx::ColorSpace::PrimaryID::CUSTOM: return media::stable::mojom::ColorSpacePrimaryID::kCustom; } NOTREACHED(); return media::stable::mojom::ColorSpacePrimaryID::kInvalid; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::ColorSpacePrimaryID input, gfx::ColorSpace::PrimaryID* output) { switch (input) { case media::stable::mojom::ColorSpacePrimaryID::kInvalid: *output = gfx::ColorSpace::PrimaryID::INVALID; return true; case media::stable::mojom::ColorSpacePrimaryID::kBT709: *output = gfx::ColorSpace::PrimaryID::BT709; return true; case media::stable::mojom::ColorSpacePrimaryID::kBT470M: *output = gfx::ColorSpace::PrimaryID::BT470M; return true; case media::stable::mojom::ColorSpacePrimaryID::kBT470BG: *output = gfx::ColorSpace::PrimaryID::BT470BG; return true; case media::stable::mojom::ColorSpacePrimaryID::kSMPTE170M: *output = gfx::ColorSpace::PrimaryID::SMPTE170M; return true; case media::stable::mojom::ColorSpacePrimaryID::kSMPTE240M: *output = gfx::ColorSpace::PrimaryID::SMPTE240M; return true; case media::stable::mojom::ColorSpacePrimaryID::kFilm: *output = gfx::ColorSpace::PrimaryID::FILM; return true; case media::stable::mojom::ColorSpacePrimaryID::kBT2020: *output = gfx::ColorSpace::PrimaryID::BT2020; return true; case media::stable::mojom::ColorSpacePrimaryID::kSMPTEST428_1: *output = gfx::ColorSpace::PrimaryID::SMPTEST428_1; return true; case media::stable::mojom::ColorSpacePrimaryID::kSMPTEST431_2: *output = gfx::ColorSpace::PrimaryID::SMPTEST431_2; return true; case media::stable::mojom::ColorSpacePrimaryID::kSMPTEST432_1: *output = gfx::ColorSpace::PrimaryID::SMPTEST432_1; return true; case media::stable::mojom::ColorSpacePrimaryID::kXYZ_D50: *output = gfx::ColorSpace::PrimaryID::XYZ_D50; return true; case media::stable::mojom::ColorSpacePrimaryID::kAdobeRGB: *output = gfx::ColorSpace::PrimaryID::ADOBE_RGB; return true; case media::stable::mojom::ColorSpacePrimaryID::kAppleGenericRGB: *output = gfx::ColorSpace::PrimaryID::APPLE_GENERIC_RGB; return true; case media::stable::mojom::ColorSpacePrimaryID::kWideGamutColorSpin: *output = gfx::ColorSpace::PrimaryID::WIDE_GAMUT_COLOR_SPIN; return true; case media::stable::mojom::ColorSpacePrimaryID::kCustom: *output = gfx::ColorSpace::PrimaryID::CUSTOM; return true; } NOTREACHED(); return false; } }; template <> struct EnumTraits<media::stable::mojom::ColorSpaceTransferID, gfx::ColorSpace::TransferID> { static media::stable::mojom::ColorSpaceTransferID ToMojom( gfx::ColorSpace::TransferID input) { switch (input) { case gfx::ColorSpace::TransferID::INVALID: return media::stable::mojom::ColorSpaceTransferID::kInvalid; case gfx::ColorSpace::TransferID::BT709: return media::stable::mojom::ColorSpaceTransferID::kBT709; case gfx::ColorSpace::TransferID::BT709_APPLE: return media::stable::mojom::ColorSpaceTransferID::kBT709Apple; case gfx::ColorSpace::TransferID::GAMMA18: return media::stable::mojom::ColorSpaceTransferID::kGamma18; case gfx::ColorSpace::TransferID::GAMMA22: return media::stable::mojom::ColorSpaceTransferID::kGamma22; case gfx::ColorSpace::TransferID::GAMMA24: return media::stable::mojom::ColorSpaceTransferID::kGamma24; case gfx::ColorSpace::TransferID::GAMMA28: return media::stable::mojom::ColorSpaceTransferID::kGamma28; case gfx::ColorSpace::TransferID::SMPTE170M: return media::stable::mojom::ColorSpaceTransferID::kSMPTE170M; case gfx::ColorSpace::TransferID::SMPTE240M: return media::stable::mojom::ColorSpaceTransferID::kSMPTE240M; case gfx::ColorSpace::TransferID::LINEAR: return media::stable::mojom::ColorSpaceTransferID::kLinear; case gfx::ColorSpace::TransferID::LOG: return media::stable::mojom::ColorSpaceTransferID::kLog; case gfx::ColorSpace::TransferID::LOG_SQRT: return media::stable::mojom::ColorSpaceTransferID::kLogSqrt; case gfx::ColorSpace::TransferID::IEC61966_2_4: return media::stable::mojom::ColorSpaceTransferID::kIEC61966_2_4; case gfx::ColorSpace::TransferID::BT1361_ECG: return media::stable::mojom::ColorSpaceTransferID::kBT1361_ECG; case gfx::ColorSpace::TransferID::IEC61966_2_1: return media::stable::mojom::ColorSpaceTransferID::kIEC61966_2_1; case gfx::ColorSpace::TransferID::BT2020_10: return media::stable::mojom::ColorSpaceTransferID::kBT2020_10; case gfx::ColorSpace::TransferID::BT2020_12: return media::stable::mojom::ColorSpaceTransferID::kBT2020_12; case gfx::ColorSpace::TransferID::SMPTEST2084: return media::stable::mojom::ColorSpaceTransferID::kSMPTEST2084; case gfx::ColorSpace::TransferID::SMPTEST428_1: return media::stable::mojom::ColorSpaceTransferID::kSMPTEST428_1; case gfx::ColorSpace::TransferID::ARIB_STD_B67: return media::stable::mojom::ColorSpaceTransferID::kARIB_STD_B67; case gfx::ColorSpace::TransferID::IEC61966_2_1_HDR: return media::stable::mojom::ColorSpaceTransferID::kIEC61966_2_1_HDR; case gfx::ColorSpace::TransferID::LINEAR_HDR: return media::stable::mojom::ColorSpaceTransferID::kLinearHDR; case gfx::ColorSpace::TransferID::CUSTOM: return media::stable::mojom::ColorSpaceTransferID::kCustom; case gfx::ColorSpace::TransferID::CUSTOM_HDR: return media::stable::mojom::ColorSpaceTransferID::kCustomHDR; case gfx::ColorSpace::TransferID::PIECEWISE_HDR: return media::stable::mojom::ColorSpaceTransferID::kPiecewiseHDR; } NOTREACHED(); return media::stable::mojom::ColorSpaceTransferID::kInvalid; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::ColorSpaceTransferID input, gfx::ColorSpace::TransferID* output) { switch (input) { case media::stable::mojom::ColorSpaceTransferID::kInvalid: *output = gfx::ColorSpace::TransferID::INVALID; return true; case media::stable::mojom::ColorSpaceTransferID::kBT709: *output = gfx::ColorSpace::TransferID::BT709; return true; case media::stable::mojom::ColorSpaceTransferID::kBT709Apple: *output = gfx::ColorSpace::TransferID::BT709_APPLE; return true; case media::stable::mojom::ColorSpaceTransferID::kGamma18: *output = gfx::ColorSpace::TransferID::GAMMA18; return true; case media::stable::mojom::ColorSpaceTransferID::kGamma22: *output = gfx::ColorSpace::TransferID::GAMMA22; return true; case media::stable::mojom::ColorSpaceTransferID::kGamma24: *output = gfx::ColorSpace::TransferID::GAMMA24; return true; case media::stable::mojom::ColorSpaceTransferID::kGamma28: *output = gfx::ColorSpace::TransferID::GAMMA28; return true; case media::stable::mojom::ColorSpaceTransferID::kSMPTE170M: *output = gfx::ColorSpace::TransferID::SMPTE170M; return true; case media::stable::mojom::ColorSpaceTransferID::kSMPTE240M: *output = gfx::ColorSpace::TransferID::SMPTE240M; return true; case media::stable::mojom::ColorSpaceTransferID::kLinear: *output = gfx::ColorSpace::TransferID::LINEAR; return true; case media::stable::mojom::ColorSpaceTransferID::kLog: *output = gfx::ColorSpace::TransferID::LOG; return true; case media::stable::mojom::ColorSpaceTransferID::kLogSqrt: *output = gfx::ColorSpace::TransferID::LOG_SQRT; return true; case media::stable::mojom::ColorSpaceTransferID::kIEC61966_2_4: *output = gfx::ColorSpace::TransferID::IEC61966_2_4; return true; case media::stable::mojom::ColorSpaceTransferID::kBT1361_ECG: *output = gfx::ColorSpace::TransferID::BT1361_ECG; return true; case media::stable::mojom::ColorSpaceTransferID::kIEC61966_2_1: *output = gfx::ColorSpace::TransferID::IEC61966_2_1; return true; case media::stable::mojom::ColorSpaceTransferID::kBT2020_10: *output = gfx::ColorSpace::TransferID::BT2020_10; return true; case media::stable::mojom::ColorSpaceTransferID::kBT2020_12: *output = gfx::ColorSpace::TransferID::BT2020_12; return true; case media::stable::mojom::ColorSpaceTransferID::kSMPTEST2084: *output = gfx::ColorSpace::TransferID::SMPTEST2084; return true; case media::stable::mojom::ColorSpaceTransferID::kSMPTEST428_1: *output = gfx::ColorSpace::TransferID::SMPTEST428_1; return true; case media::stable::mojom::ColorSpaceTransferID::kARIB_STD_B67: *output = gfx::ColorSpace::TransferID::ARIB_STD_B67; return true; case media::stable::mojom::ColorSpaceTransferID::kIEC61966_2_1_HDR: *output = gfx::ColorSpace::TransferID::IEC61966_2_1_HDR; return true; case media::stable::mojom::ColorSpaceTransferID::kLinearHDR: *output = gfx::ColorSpace::TransferID::LINEAR_HDR; return true; case media::stable::mojom::ColorSpaceTransferID::kCustom: *output = gfx::ColorSpace::TransferID::CUSTOM; return true; case media::stable::mojom::ColorSpaceTransferID::kCustomHDR: *output = gfx::ColorSpace::TransferID::CUSTOM_HDR; return true; case media::stable::mojom::ColorSpaceTransferID::kPiecewiseHDR: *output = gfx::ColorSpace::TransferID::PIECEWISE_HDR; return true; } NOTREACHED(); return false; } }; template <> struct EnumTraits<media::stable::mojom::ColorSpaceMatrixID, gfx::ColorSpace::MatrixID> { static media::stable::mojom::ColorSpaceMatrixID ToMojom( gfx::ColorSpace::MatrixID input) { switch (input) { case gfx::ColorSpace::MatrixID::INVALID: return media::stable::mojom::ColorSpaceMatrixID::kInvalid; case gfx::ColorSpace::MatrixID::RGB: return media::stable::mojom::ColorSpaceMatrixID::kRGB; case gfx::ColorSpace::MatrixID::BT709: return media::stable::mojom::ColorSpaceMatrixID::kBT709; case gfx::ColorSpace::MatrixID::FCC: return media::stable::mojom::ColorSpaceMatrixID::kFCC; case gfx::ColorSpace::MatrixID::BT470BG: return media::stable::mojom::ColorSpaceMatrixID::kBT470BG; case gfx::ColorSpace::MatrixID::SMPTE170M: return media::stable::mojom::ColorSpaceMatrixID::kSMPTE170M; case gfx::ColorSpace::MatrixID::SMPTE240M: return media::stable::mojom::ColorSpaceMatrixID::kSMPTE240M; case gfx::ColorSpace::MatrixID::YCOCG: return media::stable::mojom::ColorSpaceMatrixID::kYCOCG; case gfx::ColorSpace::MatrixID::BT2020_NCL: return media::stable::mojom::ColorSpaceMatrixID::kBT2020_NCL; case gfx::ColorSpace::MatrixID::BT2020_CL: return media::stable::mojom::ColorSpaceMatrixID::kBT2020_CL; case gfx::ColorSpace::MatrixID::YDZDX: return media::stable::mojom::ColorSpaceMatrixID::kYDZDX; case gfx::ColorSpace::MatrixID::GBR: return media::stable::mojom::ColorSpaceMatrixID::kGBR; } NOTREACHED(); return media::stable::mojom::ColorSpaceMatrixID::kInvalid; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::ColorSpaceMatrixID input, gfx::ColorSpace::MatrixID* output) { switch (input) { case media::stable::mojom::ColorSpaceMatrixID::kInvalid: *output = gfx::ColorSpace::MatrixID::INVALID; return true; case media::stable::mojom::ColorSpaceMatrixID::kRGB: *output = gfx::ColorSpace::MatrixID::RGB; return true; case media::stable::mojom::ColorSpaceMatrixID::kBT709: *output = gfx::ColorSpace::MatrixID::BT709; return true; case media::stable::mojom::ColorSpaceMatrixID::kFCC: *output = gfx::ColorSpace::MatrixID::FCC; return true; case media::stable::mojom::ColorSpaceMatrixID::kBT470BG: *output = gfx::ColorSpace::MatrixID::BT470BG; return true; case media::stable::mojom::ColorSpaceMatrixID::kSMPTE170M: *output = gfx::ColorSpace::MatrixID::SMPTE170M; return true; case media::stable::mojom::ColorSpaceMatrixID::kSMPTE240M: *output = gfx::ColorSpace::MatrixID::SMPTE240M; return true; case media::stable::mojom::ColorSpaceMatrixID::kYCOCG: *output = gfx::ColorSpace::MatrixID::YCOCG; return true; case media::stable::mojom::ColorSpaceMatrixID::kBT2020_NCL: *output = gfx::ColorSpace::MatrixID::BT2020_NCL; return true; case media::stable::mojom::ColorSpaceMatrixID::kBT2020_CL: *output = gfx::ColorSpace::MatrixID::BT2020_CL; return true; case media::stable::mojom::ColorSpaceMatrixID::kYDZDX: *output = gfx::ColorSpace::MatrixID::YDZDX; return true; case media::stable::mojom::ColorSpaceMatrixID::kGBR: *output = gfx::ColorSpace::MatrixID::GBR; return true; } NOTREACHED(); return false; } }; template <> struct EnumTraits<media::stable::mojom::ColorSpaceRangeID, gfx::ColorSpace::RangeID> { static media::stable::mojom::ColorSpaceRangeID ToMojom( gfx::ColorSpace::RangeID input) { switch (input) { case gfx::ColorSpace::RangeID::INVALID: return media::stable::mojom::ColorSpaceRangeID::kInvalid; case gfx::ColorSpace::RangeID::LIMITED: return media::stable::mojom::ColorSpaceRangeID::kLimited; case gfx::ColorSpace::RangeID::FULL: return media::stable::mojom::ColorSpaceRangeID::kFull; case gfx::ColorSpace::RangeID::DERIVED: return media::stable::mojom::ColorSpaceRangeID::kDerived; } NOTREACHED(); return media::stable::mojom::ColorSpaceRangeID::kInvalid; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::ColorSpaceRangeID input, gfx::ColorSpace::RangeID* output) { switch (input) { case media::stable::mojom::ColorSpaceRangeID::kInvalid: *output = gfx::ColorSpace::RangeID::INVALID; return true; case media::stable::mojom::ColorSpaceRangeID::kLimited: *output = gfx::ColorSpace::RangeID::LIMITED; return true; case media::stable::mojom::ColorSpaceRangeID::kFull: *output = gfx::ColorSpace::RangeID::FULL; return true; case media::stable::mojom::ColorSpaceRangeID::kDerived: *output = gfx::ColorSpace::RangeID::DERIVED; return true; } NOTREACHED(); return false; } }; template <> struct StructTraits<media::stable::mojom::ColorSpaceDataView, gfx::ColorSpace> { static gfx::ColorSpace::PrimaryID primaries(const gfx::ColorSpace& input); static gfx::ColorSpace::TransferID transfer(const gfx::ColorSpace& input); static gfx::ColorSpace::MatrixID matrix(const gfx::ColorSpace& input); static gfx::ColorSpace::RangeID range(const gfx::ColorSpace& input); static base::span<const float> custom_primary_matrix( const gfx::ColorSpace& input); static base::span<const float> transfer_params(const gfx::ColorSpace& input); static bool Read(media::stable::mojom::ColorSpaceDataView data, gfx::ColorSpace* output); }; template <> struct EnumTraits<media::stable::mojom::EncryptionScheme, ::media::EncryptionScheme> { static media::stable::mojom::EncryptionScheme ToMojom( ::media::EncryptionScheme input) { switch (input) { case ::media::EncryptionScheme::kUnencrypted: return media::stable::mojom::EncryptionScheme::kUnencrypted; case ::media::EncryptionScheme::kCenc: return media::stable::mojom::EncryptionScheme::kCenc; case ::media::EncryptionScheme::kCbcs: return media::stable::mojom::EncryptionScheme::kCbcs; } NOTREACHED(); return media::stable::mojom::EncryptionScheme::kUnencrypted; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::EncryptionScheme input, media::EncryptionScheme* output) { switch (input) { case media::stable::mojom::EncryptionScheme::kUnencrypted: *output = ::media::EncryptionScheme::kUnencrypted; return true; case media::stable::mojom::EncryptionScheme::kCenc: *output = ::media::EncryptionScheme::kCenc; return true; case media::stable::mojom::EncryptionScheme::kCbcs: *output = ::media::EncryptionScheme::kCbcs; return true; } NOTREACHED(); return false; } }; template <> struct EnumTraits<media::stable::mojom::VideoCodec, ::media::VideoCodec> { static media::stable::mojom::VideoCodec ToMojom(::media::VideoCodec input) { switch (input) { case ::media::VideoCodec::kUnknown: return media::stable::mojom::VideoCodec::kUnknown; case ::media::VideoCodec::kH264: return media::stable::mojom::VideoCodec::kH264; case ::media::VideoCodec::kVC1: return media::stable::mojom::VideoCodec::kVC1; case ::media::VideoCodec::kMPEG2: return media::stable::mojom::VideoCodec::kMPEG2; case ::media::VideoCodec::kMPEG4: return media::stable::mojom::VideoCodec::kMPEG4; case ::media::VideoCodec::kTheora: return media::stable::mojom::VideoCodec::kTheora; case ::media::VideoCodec::kVP8: return media::stable::mojom::VideoCodec::kVP8; case ::media::VideoCodec::kVP9: return media::stable::mojom::VideoCodec::kVP9; case ::media::VideoCodec::kHEVC: return media::stable::mojom::VideoCodec::kHEVC; case ::media::VideoCodec::kDolbyVision: return media::stable::mojom::VideoCodec::kDolbyVision; case ::media::VideoCodec::kAV1: return media::stable::mojom::VideoCodec::kAV1; } NOTREACHED(); return media::stable::mojom::VideoCodec::kUnknown; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::VideoCodec input, media::VideoCodec* output) { switch (input) { case media::stable::mojom::VideoCodec::kUnknown: *output = ::media::VideoCodec::kUnknown; return true; case media::stable::mojom::VideoCodec::kH264: *output = ::media::VideoCodec::kH264; return true; case media::stable::mojom::VideoCodec::kVC1: *output = ::media::VideoCodec::kVC1; return true; case media::stable::mojom::VideoCodec::kMPEG2: *output = ::media::VideoCodec::kMPEG2; return true; case media::stable::mojom::VideoCodec::kMPEG4: *output = ::media::VideoCodec::kMPEG4; return true; case media::stable::mojom::VideoCodec::kTheora: *output = ::media::VideoCodec::kTheora; return true; case media::stable::mojom::VideoCodec::kVP8: *output = ::media::VideoCodec::kVP8; return true; case media::stable::mojom::VideoCodec::kVP9: *output = ::media::VideoCodec::kVP9; return true; case media::stable::mojom::VideoCodec::kHEVC: *output = ::media::VideoCodec::kHEVC; return true; case media::stable::mojom::VideoCodec::kDolbyVision: *output = ::media::VideoCodec::kDolbyVision; return true; case media::stable::mojom::VideoCodec::kAV1: *output = ::media::VideoCodec::kAV1; return true; } NOTREACHED(); return false; } }; template <> struct EnumTraits<media::stable::mojom::VideoCodecProfile, ::media::VideoCodecProfile> { static media::stable::mojom::VideoCodecProfile ToMojom( ::media::VideoCodecProfile input) { switch (input) { case ::media::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN: return media::stable::mojom::VideoCodecProfile:: kVideoCodecProfileUnknown; case ::media::VideoCodecProfile::H264PROFILE_BASELINE: return media::stable::mojom::VideoCodecProfile::kH264ProfileBaseline; case ::media::VideoCodecProfile::H264PROFILE_MAIN: return media::stable::mojom::VideoCodecProfile::kH264ProfileMain; case ::media::VideoCodecProfile::H264PROFILE_EXTENDED: return media::stable::mojom::VideoCodecProfile::kH264ProfileExtended; case ::media::VideoCodecProfile::H264PROFILE_HIGH: return media::stable::mojom::VideoCodecProfile::kH264ProfileHigh; case ::media::VideoCodecProfile::H264PROFILE_HIGH10PROFILE: return media::stable::mojom::VideoCodecProfile::kH264ProfileHigh10; case ::media::VideoCodecProfile::H264PROFILE_HIGH422PROFILE: return media::stable::mojom::VideoCodecProfile::kH264ProfileHigh422; case ::media::VideoCodecProfile::H264PROFILE_HIGH444PREDICTIVEPROFILE: return media::stable::mojom::VideoCodecProfile:: kH264ProfileHigh444Predictive; case ::media::VideoCodecProfile::H264PROFILE_SCALABLEBASELINE: return media::stable::mojom::VideoCodecProfile:: kH264ProfileScalableBaseline; case ::media::VideoCodecProfile::H264PROFILE_SCALABLEHIGH: return media::stable::mojom::VideoCodecProfile:: kH264ProfileScalableHigh; case ::media::VideoCodecProfile::H264PROFILE_STEREOHIGH: return media::stable::mojom::VideoCodecProfile::kH264ProfileStereoHigh; case ::media::VideoCodecProfile::H264PROFILE_MULTIVIEWHIGH: return media::stable::mojom::VideoCodecProfile:: kH264ProfileMultiviewHigh; case ::media::VideoCodecProfile::VP8PROFILE_ANY: return media::stable::mojom::VideoCodecProfile::kVP8ProfileAny; case ::media::VideoCodecProfile::VP9PROFILE_PROFILE0: return media::stable::mojom::VideoCodecProfile::kVP9Profile0; case ::media::VideoCodecProfile::VP9PROFILE_PROFILE1: return media::stable::mojom::VideoCodecProfile::kVP9Profile1; case ::media::VideoCodecProfile::VP9PROFILE_PROFILE2: return media::stable::mojom::VideoCodecProfile::kVP9Profile2; case ::media::VideoCodecProfile::VP9PROFILE_PROFILE3: return media::stable::mojom::VideoCodecProfile::kVP9Profile3; case ::media::VideoCodecProfile::HEVCPROFILE_MAIN: return media::stable::mojom::VideoCodecProfile::kHEVCProfileMain; case ::media::VideoCodecProfile::HEVCPROFILE_MAIN10: return media::stable::mojom::VideoCodecProfile::kHEVCProfileMain10; case ::media::VideoCodecProfile::HEVCPROFILE_MAIN_STILL_PICTURE: return media::stable::mojom::VideoCodecProfile:: kHEVCProfileMainStillPicture; case ::media::VideoCodecProfile::DOLBYVISION_PROFILE0: return media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile0; case ::media::VideoCodecProfile::DOLBYVISION_PROFILE4: return media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile4; case ::media::VideoCodecProfile::DOLBYVISION_PROFILE5: return media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile5; case ::media::VideoCodecProfile::DOLBYVISION_PROFILE7: return media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile7; case ::media::VideoCodecProfile::THEORAPROFILE_ANY: return media::stable::mojom::VideoCodecProfile::kTheoraProfileAny; case ::media::VideoCodecProfile::AV1PROFILE_PROFILE_MAIN: return media::stable::mojom::VideoCodecProfile::kAV1ProfileMain; case ::media::VideoCodecProfile::AV1PROFILE_PROFILE_HIGH: return media::stable::mojom::VideoCodecProfile::kAV1ProfileHigh; case ::media::VideoCodecProfile::AV1PROFILE_PROFILE_PRO: return media::stable::mojom::VideoCodecProfile::kAV1ProfilePro; case ::media::VideoCodecProfile::DOLBYVISION_PROFILE8: return media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile8; case ::media::VideoCodecProfile::DOLBYVISION_PROFILE9: return media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile9; } NOTREACHED(); return media::stable::mojom::VideoCodecProfile::kVideoCodecProfileUnknown; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::VideoCodecProfile input, media::VideoCodecProfile* output) { switch (input) { case media::stable::mojom::VideoCodecProfile::kVideoCodecProfileUnknown: *output = ::media::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileBaseline: *output = ::media::VideoCodecProfile::H264PROFILE_BASELINE; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileMain: *output = ::media::VideoCodecProfile::H264PROFILE_MAIN; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileExtended: *output = ::media::VideoCodecProfile::H264PROFILE_EXTENDED; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileHigh: *output = ::media::VideoCodecProfile::H264PROFILE_HIGH; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileHigh10: *output = ::media::VideoCodecProfile::H264PROFILE_HIGH10PROFILE; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileHigh422: *output = ::media::VideoCodecProfile::H264PROFILE_HIGH422PROFILE; return true; case media::stable::mojom::VideoCodecProfile:: kH264ProfileHigh444Predictive: *output = ::media::VideoCodecProfile::H264PROFILE_HIGH444PREDICTIVEPROFILE; return true; case media::stable::mojom::VideoCodecProfile:: kH264ProfileScalableBaseline: *output = ::media::VideoCodecProfile::H264PROFILE_SCALABLEBASELINE; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileScalableHigh: *output = ::media::VideoCodecProfile::H264PROFILE_SCALABLEHIGH; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileStereoHigh: *output = ::media::VideoCodecProfile::H264PROFILE_STEREOHIGH; return true; case media::stable::mojom::VideoCodecProfile::kH264ProfileMultiviewHigh: *output = ::media::VideoCodecProfile::H264PROFILE_MULTIVIEWHIGH; return true; case media::stable::mojom::VideoCodecProfile::kVP8ProfileAny: *output = ::media::VideoCodecProfile::VP8PROFILE_ANY; return true; case media::stable::mojom::VideoCodecProfile::kVP9Profile0: *output = ::media::VideoCodecProfile::VP9PROFILE_PROFILE0; return true; case media::stable::mojom::VideoCodecProfile::kVP9Profile1: *output = ::media::VideoCodecProfile::VP9PROFILE_PROFILE1; return true; case media::stable::mojom::VideoCodecProfile::kVP9Profile2: *output = ::media::VideoCodecProfile::VP9PROFILE_PROFILE2; return true; case media::stable::mojom::VideoCodecProfile::kVP9Profile3: *output = ::media::VideoCodecProfile::VP9PROFILE_PROFILE3; return true; case media::stable::mojom::VideoCodecProfile::kHEVCProfileMain: *output = ::media::VideoCodecProfile::HEVCPROFILE_MAIN; return true; case media::stable::mojom::VideoCodecProfile::kHEVCProfileMain10: *output = ::media::VideoCodecProfile::HEVCPROFILE_MAIN10; return true; case media::stable::mojom::VideoCodecProfile:: kHEVCProfileMainStillPicture: *output = ::media::VideoCodecProfile::HEVCPROFILE_MAIN_STILL_PICTURE; return true; case media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile0: *output = ::media::VideoCodecProfile::DOLBYVISION_PROFILE0; return true; case media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile4: *output = ::media::VideoCodecProfile::DOLBYVISION_PROFILE4; return true; case media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile5: *output = ::media::VideoCodecProfile::DOLBYVISION_PROFILE5; return true; case media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile7: *output = ::media::VideoCodecProfile::DOLBYVISION_PROFILE7; return true; case media::stable::mojom::VideoCodecProfile::kTheoraProfileAny: *output = ::media::VideoCodecProfile::THEORAPROFILE_ANY; return true; case media::stable::mojom::VideoCodecProfile::kAV1ProfileMain: *output = ::media::VideoCodecProfile::AV1PROFILE_PROFILE_MAIN; return true; case media::stable::mojom::VideoCodecProfile::kAV1ProfileHigh: *output = ::media::VideoCodecProfile::AV1PROFILE_PROFILE_HIGH; return true; case media::stable::mojom::VideoCodecProfile::kAV1ProfilePro: *output = ::media::VideoCodecProfile::AV1PROFILE_PROFILE_PRO; return true; case media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile8: *output = ::media::VideoCodecProfile::DOLBYVISION_PROFILE8; return true; case media::stable::mojom::VideoCodecProfile::kDolbyVisionProfile9: *output = ::media::VideoCodecProfile::DOLBYVISION_PROFILE9; return true; } NOTREACHED(); return false; } }; template <> struct EnumTraits<media::stable::mojom::VideoDecoderType, ::media::VideoDecoderType> { static media::stable::mojom::VideoDecoderType ToMojom( ::media::VideoDecoderType input) { switch (input) { case ::media::VideoDecoderType::kVaapi: return media::stable::mojom::VideoDecoderType::kVaapi; case ::media::VideoDecoderType::kVda: return media::stable::mojom::VideoDecoderType::kVda; case ::media::VideoDecoderType::kV4L2: return media::stable::mojom::VideoDecoderType::kV4L2; case ::media::VideoDecoderType::kTesting: return media::stable::mojom::VideoDecoderType::kTesting; case ::media::VideoDecoderType::kUnknown: case ::media::VideoDecoderType::kFFmpeg: case ::media::VideoDecoderType::kVpx: case ::media::VideoDecoderType::kAom: case ::media::VideoDecoderType::kMojo: case ::media::VideoDecoderType::kDecrypting: case ::media::VideoDecoderType::kDav1d: case ::media::VideoDecoderType::kFuchsia: case ::media::VideoDecoderType::kMediaCodec: case ::media::VideoDecoderType::kGav1: case ::media::VideoDecoderType::kD3D11: case ::media::VideoDecoderType::kBroker: return media::stable::mojom::VideoDecoderType::kUnknown; } NOTREACHED(); return media::stable::mojom::VideoDecoderType::kUnknown; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::VideoDecoderType input, ::media::VideoDecoderType* output) { switch (input) { case media::stable::mojom::VideoDecoderType::kVaapi: *output = ::media::VideoDecoderType::kVaapi; return true; case media::stable::mojom::VideoDecoderType::kVda: *output = ::media::VideoDecoderType::kVda; return true; case media::stable::mojom::VideoDecoderType::kV4L2: *output = ::media::VideoDecoderType::kV4L2; return true; case media::stable::mojom::VideoDecoderType::kTesting: *output = ::media::VideoDecoderType::kTesting; return true; case media::stable::mojom::VideoDecoderType::kUnknown: *output = ::media::VideoDecoderType::kUnknown; return true; } NOTREACHED(); return false; } }; template <> struct EnumTraits<media::stable::mojom::VideoPixelFormat, ::media::VideoPixelFormat> { static media::stable::mojom::VideoPixelFormat ToMojom( ::media::VideoPixelFormat input) { switch (input) { case ::media::VideoPixelFormat::PIXEL_FORMAT_UNKNOWN: return media::stable::mojom::VideoPixelFormat::kPixelFormatUnknown; case ::media::VideoPixelFormat::PIXEL_FORMAT_I420: return media::stable::mojom::VideoPixelFormat::kPixelFormatI420; case ::media::VideoPixelFormat::PIXEL_FORMAT_YV12: return media::stable::mojom::VideoPixelFormat::kPixelFormatYV12; case ::media::VideoPixelFormat::PIXEL_FORMAT_I422: return media::stable::mojom::VideoPixelFormat::kPixelFormatI422; case ::media::VideoPixelFormat::PIXEL_FORMAT_I420A: return media::stable::mojom::VideoPixelFormat::kPixelFormatI420A; case ::media::VideoPixelFormat::PIXEL_FORMAT_I444: return media::stable::mojom::VideoPixelFormat::kPixelFormatI444; case ::media::VideoPixelFormat::PIXEL_FORMAT_NV12: return media::stable::mojom::VideoPixelFormat::kPixelFormatNV12; case ::media::VideoPixelFormat::PIXEL_FORMAT_NV21: return media::stable::mojom::VideoPixelFormat::kPixelFormatNV21; case ::media::VideoPixelFormat::PIXEL_FORMAT_UYVY: return media::stable::mojom::VideoPixelFormat::kPixelFormatUYVY; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUY2: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUY2; case ::media::VideoPixelFormat::PIXEL_FORMAT_ARGB: return media::stable::mojom::VideoPixelFormat::kPixelFormatARGB; case ::media::VideoPixelFormat::PIXEL_FORMAT_XRGB: return media::stable::mojom::VideoPixelFormat::kPixelFormatXRGB; case ::media::VideoPixelFormat::PIXEL_FORMAT_RGB24: return media::stable::mojom::VideoPixelFormat::kPixelFormatRGB24; case ::media::VideoPixelFormat::PIXEL_FORMAT_MJPEG: return media::stable::mojom::VideoPixelFormat::kPixelFormatMJPEG; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV420P9: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV420P9; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV420P10: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV420P10; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV422P9: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV422P9; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV422P10: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV422P10; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV444P9: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV444P9; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV444P10: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV444P10; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV420P12: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV420P12; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV422P12: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV422P12; case ::media::VideoPixelFormat::PIXEL_FORMAT_YUV444P12: return media::stable::mojom::VideoPixelFormat::kPixelFormatYUV444P12; case ::media::VideoPixelFormat::PIXEL_FORMAT_Y16: return media::stable::mojom::VideoPixelFormat::kPixelFormatY16; case ::media::VideoPixelFormat::PIXEL_FORMAT_ABGR: return media::stable::mojom::VideoPixelFormat::kPixelFormatABGR; case ::media::VideoPixelFormat::PIXEL_FORMAT_XBGR: return media::stable::mojom::VideoPixelFormat::kPixelFormatXBGR; case ::media::VideoPixelFormat::PIXEL_FORMAT_P016LE: return media::stable::mojom::VideoPixelFormat::kPixelFormatP016LE; case ::media::VideoPixelFormat::PIXEL_FORMAT_XR30: return media::stable::mojom::VideoPixelFormat::kPixelFormatXR30; case ::media::VideoPixelFormat::PIXEL_FORMAT_XB30: return media::stable::mojom::VideoPixelFormat::kPixelFormatXB30; case ::media::VideoPixelFormat::PIXEL_FORMAT_BGRA: return media::stable::mojom::VideoPixelFormat::kPixelFormatBGRA; case ::media::VideoPixelFormat::PIXEL_FORMAT_RGBAF16: return media::stable::mojom::VideoPixelFormat::kPixelFormatRGBAF16; } NOTREACHED(); return media::stable::mojom::VideoPixelFormat::kPixelFormatUnknown; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::VideoPixelFormat input, ::media::VideoPixelFormat* output) { switch (input) { case media::stable::mojom::VideoPixelFormat::kPixelFormatUnknown: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_UNKNOWN; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatI420: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_I420; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYV12: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YV12; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatI422: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_I422; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatI420A: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_I420A; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatI444: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_I444; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatNV12: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_NV12; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatNV21: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_NV21; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatUYVY: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_UYVY; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUY2: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUY2; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatARGB: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_ARGB; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatXRGB: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_XRGB; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatRGB24: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_RGB24; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatMJPEG: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_MJPEG; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV420P9: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV420P9; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV420P10: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV420P10; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV422P9: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV422P9; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV422P10: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV422P10; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV444P9: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV444P9; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV444P10: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV444P10; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV420P12: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV420P12; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV422P12: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV422P12; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatYUV444P12: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_YUV444P12; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatY16: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_Y16; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatABGR: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_ABGR; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatXBGR: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_XBGR; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatP016LE: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_P016LE; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatXR30: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_XR30; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatXB30: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_XB30; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatBGRA: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_BGRA; return true; case media::stable::mojom::VideoPixelFormat::kPixelFormatRGBAF16: *output = ::media::VideoPixelFormat::PIXEL_FORMAT_RGBAF16; return true; } NOTREACHED(); return false; } }; template <> struct EnumTraits<media::stable::mojom::WaitingReason, media::WaitingReason> { static media::stable::mojom::WaitingReason ToMojom( media::WaitingReason input) { switch (input) { case media::WaitingReason::kNoCdm: return media::stable::mojom::WaitingReason::kNoCdm; case media::WaitingReason::kNoDecryptionKey: return media::stable::mojom::WaitingReason::kNoDecryptionKey; case media::WaitingReason::kDecoderStateLost: return media::stable::mojom::WaitingReason::kDecoderStateLost; } NOTREACHED(); return media::stable::mojom::WaitingReason::kNoCdm; } // Returning false results in deserialization failure and causes the // message pipe receiving it to be disconnected. static bool FromMojom(media::stable::mojom::WaitingReason input, media::WaitingReason* output) { switch (input) { case media::stable::mojom::WaitingReason::kNoCdm: *output = media::WaitingReason::kNoCdm; return true; case media::stable::mojom::WaitingReason::kNoDecryptionKey: *output = media::WaitingReason::kNoDecryptionKey; return true; case media::stable::mojom::WaitingReason::kDecoderStateLost: *output = media::WaitingReason::kDecoderStateLost; return true; } NOTREACHED(); return false; } }; template <> struct StructTraits<media::stable::mojom::SubsampleEntryDataView, ::media::SubsampleEntry> { static uint32_t clear_bytes(const ::media::SubsampleEntry& input); static uint32_t cypher_bytes(const ::media::SubsampleEntry& input); static bool Read(media::stable::mojom::SubsampleEntryDataView input, ::media::SubsampleEntry* output); }; } // namespace mojo #endif // MEDIA_MOJO_MOJOM_STABLE_STABLE_VIDEO_DECODER_TYPES_MOJOM_TRAITS_H_
blueboxd/chromium-legacy
services/audio/output_mixer.h
<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_AUDIO_OUTPUT_MIXER_H_ #define SERVICES_AUDIO_OUTPUT_MIXER_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/task/single_thread_task_runner.h" #include "media/base/audio_parameters.h" #include "services/audio/reference_output.h" namespace media { class AudioOutputStream; } namespace audio { // Manages mixing and rendering of all audio outputs going to a specific output // device. As ReferenceOutput provides to Listeners an ability to listen to the // audio mix being rendered. If there is at least one listener connected, the // mixer is mixing all the audio output and rendering the mix as a single audio // output stream. Otherwise the streams are rendered independently. class OutputMixer : public ReferenceOutput { public: // Callback to be used by OutputMixer to create actual output streams playing // audio. using CreateStreamCallback = base::RepeatingCallback<media::AudioOutputStream*( const std::string& device_id, const media::AudioParameters& params)>; // A helper class for the clients to pass OutputMixer::Create around as a // callback. using CreateCallback = base::RepeatingCallback<std::unique_ptr<OutputMixer>( const std::string& device_id, const media::AudioParameters& output_params, CreateStreamCallback create_stream_callback, scoped_refptr<base::SingleThreadTaskRunner> task_runner)>; // Creates OutputMixer which manages playback to the device identified by // |device_id|. |output_params| - parameters for the audio mix playback; // |create_stream_callback| will be used by OutputMixer to create output // streams playing audio; |task_runner| is the main task runner of // OutputMixer. static std::unique_ptr<OutputMixer> Create( const std::string& device_id, const media::AudioParameters& output_params, CreateStreamCallback create_stream_callback, scoped_refptr<base::SingleThreadTaskRunner> task_runner); // |device_id| is the id of the output device to manage the playback to. explicit OutputMixer(const std::string& device_id); OutputMixer(const OutputMixer&) = delete; OutputMixer& operator=(const OutputMixer&) = delete; // Id of the device audio output to which is managed by OutputMixer. const std::string& device_id() const { return device_id_; } // Creates an audio output stream managed by the given OutputMixer. // |params| - output stream parameters; |on_device_change_callback| - callback // to notify the AudioOutputStream client about device change events observed // by OutputMixer. virtual media::AudioOutputStream* MakeMixableStream( const media::AudioParameters& params, base::OnceCallback<void()> on_device_change_callback) = 0; // Notify OutputMixer about the device change event. virtual void ProcessDeviceChange() = 0; private: // Id of the device output to which is managed by the mixer. const std::string device_id_; }; } // namespace audio #endif // SERVICES_AUDIO_OUTPUT_MIXER_H_
blueboxd/chromium-legacy
components/password_manager/core/common/password_manager_features.h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_PASSWORD_MANAGER_CORE_COMMON_PASSWORD_MANAGER_FEATURES_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_COMMON_PASSWORD_MANAGER_FEATURES_H_ // This file defines all the base::FeatureList features for the Password Manager // module. #include "base/feature_list.h" #include "build/build_config.h" namespace password_manager { namespace features { // All features in alphabetical order. The features should be documented // alongside the definition of their values in the .cc file. extern const base::Feature kBiometricTouchToFill; extern const base::Feature kEditPasswordsInSettings; extern const base::Feature kDetectFormSubmissionOnFormClear; extern const base::Feature kEnableManualPasswordGeneration; extern const base::Feature kEnableMovingMultiplePasswordsToAccount; extern const base::Feature kEnableOverwritingPlaceholderUsernames; extern const base::Feature kEnablePasswordsAccountStorage; extern const base::Feature KEnablePasswordGenerationForClearTextFields; extern const base::Feature kFillingAcrossAffiliatedWebsites; extern const base::Feature kFillOnAccountSelect; extern const base::Feature kInferConfirmationPasswordField; extern const base::Feature kPasswordChange; extern const base::Feature kPasswordChangeInSettings; extern const base::Feature kPasswordImport; extern const base::Feature kPasswordReuseDetectionEnabled; extern const base::Feature kPasswordsAccountStorageRevisedOptInFlow; extern const base::Feature kPasswordScriptsFetching; extern const base::Feature kRecoverFromNeverSaveAndroid; extern const base::Feature kReparseServerPredictionsFollowingFormChange; extern const base::Feature kSecondaryServerFieldPredictions; extern const base::Feature kSupportForAddPasswordsInSettings; extern const base::Feature kTreatNewPasswordHeuristicsAsReliable; #if defined(OS_ANDROID) extern const base::Feature kUnifiedPasswordManagerAndroid; extern const base::Feature kUnifiedPasswordManagerMigration; extern const base::Feature kUnifiedPasswordManagerShadowAndroid; extern const base::Feature kUnifiedPasswordManagerSyncUsingAndroidBackendOnly; #endif extern const base::Feature kUsernameFirstFlow; extern const base::Feature kUsernameFirstFlowFilling; extern const base::Feature kUsernameFirstFlowFallbackCrowdsourcing; // All features parameters are in alphabetical order. #if defined(OS_ANDROID) extern const base::FeatureParam<int> kMigrationVersion; #endif // Field trial and corresponding parameters. // To manually override this, start Chrome with the following parameters: // --enable-features=PasswordGenerationRequirements,\ // PasswordGenerationRequirementsDomainOverrides // --force-fieldtrials=PasswordGenerationRequirements/Enabled // --force-fieldtrial-params=PasswordGenerationRequirements.Enabled:\ // version/0/prefix_length/0/timeout/5000 extern const char kGenerationRequirementsFieldTrial[]; extern const char kGenerationRequirementsVersion[]; extern const char kGenerationRequirementsPrefixLength[]; extern const char kGenerationRequirementsTimeout[]; // Password change feature variations. extern const char kPasswordChangeWithForcedDialogAfterEverySuccessfulSubmission[]; extern const char kPasswordChangeInSettingsWithForcedWarningForEverySite[]; } // namespace features } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_COMMON_PASSWORD_MANAGER_FEATURES_H_
blueboxd/chromium-legacy
content/browser/loader/navigation_url_loader.h
<filename>content/browser/loader/navigation_url_loader.h<gh_stars>10-100 // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_LOADER_NAVIGATION_URL_LOADER_H_ #define CONTENT_BROWSER_LOADER_NAVIGATION_URL_LOADER_H_ #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "content/browser/loader/navigation_loader_interceptor.h" #include "content/common/content_export.h" #include "services/network/public/mojom/devtools_observer.mojom-forward.h" #include "third_party/blink/public/common/loader/previews_state.h" namespace net { class HttpRequestHeaders; } namespace content { class BrowserContext; class NavigationUIData; class NavigationURLLoaderDelegate; class NavigationURLLoaderFactory; class PrefetchedSignedExchangeCache; class ServiceWorkerMainResourceHandle; class StoragePartition; struct NavigationRequestInfo; // The navigation logic's UI thread entry point into the resource loading stack. // It exposes an interface to control the request prior to receiving the // response. If the NavigationURLLoader is destroyed before OnResponseStarted is // called, the request is aborted. class CONTENT_EXPORT NavigationURLLoader { public: enum class LoaderType { // Creates a regular NavigationURLLoader. kRegular, // Creates a noop NavigationURLLoader for BackForwardCache activation. kNoopForBackForwardCache, // Creates a noop NavigationURLLoader for Prerender activation. kNoopForPrerender, }; // Creates a NavigationURLLoader. The caller is responsible for ensuring that // `delegate` outlives the loader. `request_body` must not be accessed on the // UI thread after this point. // // If `loader_type` is LoaderType::kNoopForBackForwardCache or // LoaderType::kNoopoForPrerender, a noop CachedNavigationURLLoader will be // returned. // // TODO(davidben): When navigation is disentangled from the loader, the // request parameters should not come in as a navigation-specific // structure. Information like `has_user_gesture` and // `should_replace_current_entry` in `request_info->common_params` shouldn't // be needed at this layer. static std::unique_ptr<NavigationURLLoader> Create( BrowserContext* browser_context, StoragePartition* storage_partition, std::unique_ptr<NavigationRequestInfo> request_info, std::unique_ptr<NavigationUIData> navigation_ui_data, ServiceWorkerMainResourceHandle* service_worker_handle, scoped_refptr<PrefetchedSignedExchangeCache> prefetched_signed_exchange_cache, NavigationURLLoaderDelegate* delegate, LoaderType loader_type, mojo::PendingRemote<network::mojom::CookieAccessObserver> cookie_observer, mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver> url_loader_network_observer, mojo::PendingRemote<network::mojom::DevToolsObserver> devtools_observer, network::mojom::URLResponseHeadPtr cached_response_head = nullptr, std::vector<std::unique_ptr<NavigationLoaderInterceptor>> initial_interceptors = {}); // For testing purposes; sets the factory for use in testing. The factory is // not used for prerendered page activation as it needs to run a specific // loader to satisfy its unique requirement. See the implementation comment in // NavigationURLLoader::Create() for details. // TODO(https://crbug.com/1226442): Update this comment for restoration from // BackForwardCache when it also starts depending on the requirement. static void SetFactoryForTesting(NavigationURLLoaderFactory* factory); NavigationURLLoader(const NavigationURLLoader&) = delete; NavigationURLLoader& operator=(const NavigationURLLoader&) = delete; virtual ~NavigationURLLoader() {} // Called right after the loader is constructed. virtual void Start() = 0; // Called in response to OnRequestRedirected to continue processing the // request. `new_previews_state` will be updated for newly created URLLoaders, // but the existing default URLLoader will not see `new_previews_state` unless // the URLLoader happens to be reset. virtual void FollowRedirect( const std::vector<std::string>& removed_headers, const net::HttpRequestHeaders& modified_headers, const net::HttpRequestHeaders& modified_cors_exempt_headers, blink::PreviewsState new_previews_state) = 0; // Sets an overall request timeout for this navigation, which will cause the // navigation to fail if it expires before the navigation commits. This is // separate from any //net level timeouts. Returns `true` if the timeout was // started successfully. Repeated calls will be ignored (they won't reset the // timeout) and will return `false`. virtual bool SetNavigationTimeout(base::TimeDelta timeout) = 0; protected: NavigationURLLoader() {} }; } // namespace content #endif // CONTENT_BROWSER_LOADER_NAVIGATION_URL_LOADER_H_
blueboxd/chromium-legacy
content/renderer/accessibility/render_accessibility_impl.h
<gh_stars>10-100 // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_RENDERER_ACCESSIBILITY_RENDER_ACCESSIBILITY_IMPL_H_ #define CONTENT_RENDERER_ACCESSIBILITY_RENDER_ACCESSIBILITY_IMPL_H_ #include <list> #include <memory> #include <vector> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "content/common/content_export.h" #include "content/common/render_accessibility.mojom.h" #include "content/public/renderer/plugin_ax_tree_source.h" #include "content/public/renderer/render_accessibility.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_observer.h" #include "content/renderer/accessibility/blink_ax_tree_source.h" #include "third_party/blink/public/web/web_ax_context.h" #include "third_party/blink/public/web/web_ax_object.h" #include "ui/accessibility/ax_event.h" #include "ui/accessibility/ax_node_data.h" #include "ui/accessibility/ax_relative_bounds.h" #include "ui/accessibility/ax_tree.h" #include "ui/accessibility/ax_tree_data.h" #include "ui/accessibility/ax_tree_serializer.h" #include "ui/accessibility/ax_tree_update.h" #include "ui/gfx/geometry/rect_f.h" namespace base { class ElapsedTimer; } // namespace base namespace blink { class WebDocument; } // namespace blink namespace ui { struct AXActionData; class AXActionTarget; struct AXEvent; } namespace ukm { class MojoUkmRecorder; } namespace content { class AXImageAnnotator; class RenderFrameImpl; class RenderAccessibilityManager; using BlinkAXTreeSerializer = ui::AXTreeSerializer<blink::WebAXObject>; struct AXDirtyObject { AXDirtyObject(); AXDirtyObject(const AXDirtyObject& other); ~AXDirtyObject(); blink::WebAXObject obj; ax::mojom::EventFrom event_from; ax::mojom::Action event_from_action; std::vector<ui::AXEventIntent> event_intents; }; // The browser process implements native accessibility APIs, allowing assistive // technology (e.g., screen readers, magnifiers) to access and control the web // contents with high-level APIs. These APIs are also used by automation tools, // and Windows 8 uses them to determine when the on-screen keyboard should be // shown. // // An instance of this class belongs to the RenderAccessibilityManager object. // Accessibility is initialized based on the ui::AXMode passed from the browser // process to the manager object; it lazily starts as Off or EditableTextOnly // depending on the operating system, and switches to Complete if assistive // technology is detected or a flag is set. // // A tree of accessible objects is built here and sent to the browser process; // the browser process maintains this as a tree of platform-native accessible // objects that can be used to respond to accessibility requests from other // processes. // // This class implements complete accessibility support for assistive // technology. It turns on Blink's accessibility code and sends a serialized // representation of that tree whenever it changes. It also handles requests // from the browser to perform accessibility actions on nodes in the tree (e.g., // change focus, or click on a button). class CONTENT_EXPORT RenderAccessibilityImpl : public RenderAccessibility, public RenderFrameObserver { public: RenderAccessibilityImpl( RenderAccessibilityManager* const render_accessibility_manager, RenderFrameImpl* const render_frame, ui::AXMode mode); RenderAccessibilityImpl(const RenderAccessibilityImpl&) = delete; RenderAccessibilityImpl& operator=(const RenderAccessibilityImpl&) = delete; ~RenderAccessibilityImpl() override; ui::AXMode GetAccessibilityMode() { return tree_source_->accessibility_mode(); } // RenderAccessibility implementation. int GenerateAXID() override; void SetPluginTreeSource(PluginAXTreeSource* source) override; void OnPluginRootNodeUpdated() override; void ShowPluginContextMenu() override; // RenderFrameObserver implementation. void DidCreateNewDocument() override; void DidCommitProvisionalLoad(ui::PageTransition transition) override; void AccessibilityModeChanged(const ui::AXMode& mode) override; void HitTest(const gfx::Point& point, ax::mojom::Event event_to_fire, int request_id, mojom::RenderAccessibility::HitTestCallback callback); void PerformAction(const ui::AXActionData& data); void Reset(int32_t reset_token); // Called when an accessibility notification occurs in Blink. void HandleAXEvent(const ui::AXEvent& event); void MarkWebAXObjectDirty( const blink::WebAXObject& obj, bool subtree, ax::mojom::Action event_from_action = ax::mojom::Action::kNone, std::vector<ui::AXEventIntent> event_intents = {}, ax::mojom::Event event_type = ax::mojom::Event::kNone); // Returns the main top-level document for this page, or NULL if there's // no view or frame. blink::WebDocument GetMainDocument(); // Returns the page language. std::string GetLanguage(); // Access the UKM recorder. ukm::MojoUkmRecorder* ukm_recorder() const { return ukm_recorder_.get(); } // Called when the renderer has closed the connection to reset the state // machine. void ConnectionClosed(); protected: // Send queued events from the renderer to the browser. void SendPendingAccessibilityEvents(); // Check the entire accessibility tree to see if any nodes have // changed location, by comparing their locations to the cached // versions. If any have moved, send an IPC with the new locations. void SendLocationChanges(); // Return true if the event indicates that the current batch of changes // should be processed immediately in order for the user to get fast // feedback, e.g. for navigation or data entry activities. bool IsImmediateProcessingRequiredForEvent(const ui::AXEvent&) const; // Get the amount of time, in ms, that event processing should be deferred // in order to more efficiently batch changes. int GetDeferredEventsDelay(); private: enum class EventScheduleMode { kDeferEvents, kProcessEventsImmediately }; enum class EventScheduleStatus { // Events have been scheduled with a delay, but have not been sent. kScheduledDeferred, // Events have been scheduled without a delay, but have not been sent. kScheduledImmediate, // Events have been sent, waiting for callback. kWaitingForAck, // Events are not scheduled and we are not waiting for an ack. kNotWaiting }; // Add an AXDirtyObject to the dirty_objects_ queue. // Returns an iterator pointing just after the newly inserted object. std::list<std::unique_ptr<AXDirtyObject>>::iterator EnqueueDirtyObject( const blink::WebAXObject& obj, ax::mojom::EventFrom event_from, ax::mojom::Action event_from_action, std::vector<ui::AXEventIntent> event_intents, std::list<std::unique_ptr<AXDirtyObject>>::iterator insertion_point); // Callback that will be called from the browser upon handling the message // previously sent to it via SendPendingAccessibilityEvents(). void OnAccessibilityEventsHandled(); // RenderFrameObserver implementation. void OnDestruct() override; // Handlers for messages from the browser to the renderer. void OnLoadInlineTextBoxes(const ui::AXActionTarget* target); void OnGetImageData(const ui::AXActionTarget* target, const gfx::Size& max_size); void AddPluginTreeToUpdate(ui::AXTreeUpdate* update, bool invalidate_plugin_subtree); // Creates and takes ownership of an instance of the class that automatically // labels images for accessibility. void CreateAXImageAnnotator(); // Automatically labels images for accessibility if the accessibility mode for // this feature is turned on, otherwise stops automatic labeling and removes // any automatic annotations that might have been added before. void StartOrStopLabelingImages(ui::AXMode old_mode, ui::AXMode new_mode); // Marks all AXObjects with the given role in the current tree dirty. void MarkAllAXObjectsDirty(ax::mojom::Role role, ax::mojom::Action event_from_action); void Scroll(const ui::AXActionTarget* target, ax::mojom::Action scroll_action); // Whether an event should mark its associated object dirty. bool ShouldSerializeNodeForEvent(const blink::WebAXObject& obj, const ui::AXEvent& event) const; // If we are calling this from a task, scheduling is allowed even if there is // a running task void ScheduleSendPendingAccessibilityEvents( bool scheduling_from_task = false); void AddImageAnnotationDebuggingAttributes( const std::vector<ui::AXTreeUpdate>& updates); // Returns the document for the active popup if any. blink::WebDocument GetPopupDocument(); // Searches the accessibility tree for plugin's root object and returns it. // Returns an empty WebAXObject if no root object is present. blink::WebAXObject GetPluginRoot(); // Cancels scheduled events that are not yet in flight void CancelScheduledEvents(); // Sends the URL-keyed metrics for the maximum amount of time spent in // SendPendingAccessibilityEvents if they meet the minimum criteria for // sending. void MaybeSendUKM(); // Reset all of the UKM data. This can be called after sending UKM data, // or after navigating to a new page when any previous data will no // longer be valid. void ResetUKMData(); bool SerializeUpdatesAndEvents(blink::WebDocument document, blink::WebAXObject root, std::vector<ui::AXEvent>& events, std::vector<ui::AXTreeUpdate>& updates, bool invalidate_plugin_subtree); // The initial accessibility tree root still needs to be created. Like other // accessible objects, it must be created when layout is clean. bool needs_initial_ax_tree_root_ = true; // The RenderAccessibilityManager that owns us. RenderAccessibilityManager* render_accessibility_manager_; // The associated RenderFrameImpl by means of the RenderAccessibilityManager. RenderFrameImpl* render_frame_; // This keeps accessibility enabled as long as it lives. std::unique_ptr<blink::WebAXContext> ax_context_; // Manages the automatic image annotations, if enabled. std::unique_ptr<AXImageAnnotator> ax_image_annotator_; // Events from Blink are collected until they are ready to be // sent to the browser. std::vector<ui::AXEvent> pending_events_; // Objects that need to be re-serialized, the next time // we send an event bundle to the browser - but don't specifically need // an event fired. std::list<std::unique_ptr<AXDirtyObject>> dirty_objects_; // The adapter that exposes Blink's accessibility tree to AXTreeSerializer. std::unique_ptr<BlinkAXTreeSource> tree_source_; // The serializer that sends accessibility messages to the browser process. std::unique_ptr<BlinkAXTreeSerializer> serializer_; using PluginAXTreeSerializer = ui::AXTreeSerializer<const ui::AXNode*>; std::unique_ptr<PluginAXTreeSerializer> plugin_serializer_; PluginAXTreeSource* plugin_tree_source_; blink::WebAXObject plugin_host_node_; // Current event scheduling status EventScheduleStatus event_schedule_status_; // Nonzero if the browser requested we reset the accessibility state. // We need to return this token in the next IPC. int reset_token_; // Whether or not we've injected a stylesheet in this document // (only when debugging flags are enabled, never under normal circumstances). bool has_injected_stylesheet_ = false; // We defer events to improve performance during the initial page load. EventScheduleMode event_schedule_mode_; // Whether we should highlight annotation results visually on the page // for debugging. bool image_annotation_debugging_ = false; // The specified page language, or empty if unknown. std::string page_language_; // The URL-keyed metrics recorder interface. std::unique_ptr<ukm::MojoUkmRecorder> ukm_recorder_; // The longest amount of time spent serializing the accessibility tree // in SendPendingAccessibilityEvents. This is periodically uploaded as // a UKM and then reset. base::TimeDelta slowest_serialization_time_; // The amount of time since the last UKM upload. std::unique_ptr<base::ElapsedTimer> ukm_timer_; // The UKM Source ID that corresponds to the web page represented by // slowest_serialization_ms_. We report UKM before the user navigates // away, or every few minutes. ukm::SourceId last_ukm_source_id_; // So we can queue up tasks to be executed later. base::WeakPtrFactory<RenderAccessibilityImpl> weak_factory_for_pending_events_{this}; friend class AXImageAnnotatorTest; friend class PluginActionHandlingTest; friend class RenderAccessibilityImplTest; friend class RenderAccessibilityImplUKMTest; }; } // namespace content #endif // CONTENT_RENDERER_ACCESSIBILITY_RENDER_ACCESSIBILITY_IMPL_H_
blueboxd/chromium-legacy
chrome/browser/policy/messaging_layer/public/report_client.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_PUBLIC_REPORT_CLIENT_H_ #define CHROME_BROWSER_POLICY_MESSAGING_LAYER_PUBLIC_REPORT_CLIENT_H_ #include <memory> #include <queue> #include <utility> #include "base/callback.h" #include "base/memory/singleton.h" #include "chrome/browser/policy/messaging_layer/upload/upload_client.h" #include "chrome/browser/policy/messaging_layer/upload/upload_provider.h" #include "chrome/browser/policy/messaging_layer/util/get_cloud_policy_client.h" #include "components/reporting/client/report_queue_configuration.h" #include "components/reporting/client/report_queue_provider.h" #include "components/reporting/proto/synced/record.pb.h" #include "components/reporting/storage/storage_module_interface.h" #include "components/reporting/storage/storage_uploader_interface.h" #include "components/reporting/storage_selector/storage_selector.h" #include "components/reporting/util/shared_queue.h" #include "components/reporting/util/statusor.h" namespace reporting { // ReportingClient is an implementation of ReportQueueProvider for Chrome // (currently only primary Chrome is supported, and so the client expects // cloud policy client to be available and creates an uploader to use it. class ReportingClient : public ReportQueueProvider { public: using CreateReportQueueResponse = StatusOr<std::unique_ptr<ReportQueue>>; using CreateReportQueueCallback = base::OnceCallback<void(CreateReportQueueResponse)>; // RAII class for testing ReportingClient - substitutes reporting files // location, signature verification public key and a cloud policy client // builder to return given client. Resets client when destructed. class TestEnvironment { public: TestEnvironment(const base::FilePath& reporting_path, base::StringPiece verification_key, policy::CloudPolicyClient* client); TestEnvironment(const TestEnvironment& other) = delete; TestEnvironment& operator=(const TestEnvironment& other) = delete; ~TestEnvironment(); private: StorageModuleCreateCallback saved_storage_create_cb_; GetCloudPolicyClientCallback saved_build_cloud_policy_client_cb_; std::unique_ptr<EncryptedReportingUploadProvider> saved_upload_provider_; }; ~ReportingClient() override; ReportingClient(const ReportingClient& other) = delete; ReportingClient& operator=(const ReportingClient& other) = delete; private: class Uploader; friend class TestEnvironment; friend class ReportQueueProvider; friend struct base::DefaultSingletonTraits<ReportingClient>; // Constructor to be used by singleton only. ReportingClient(); // Accesses singleton ReportingClient instance. // Separate from ReportQueueProvider::GetInstance, because // Singleton<ReportingClient>::get() can only be used inside ReportingClient // class. static ReportingClient* GetInstance(); void OnInitState(bool reporting_client_configured); void OnInitializationComplete(Status init_status); static void AsyncStartUploader( UploaderInterface::UploadReason reason, UploaderInterface::UploaderInterfaceResultCb start_uploader_cb); void DeliverAsyncStartUploader( UploaderInterface::UploadReason reason, UploaderInterface::UploaderInterfaceResultCb start_uploader_cb); // Returns default upload provider for the client. std::unique_ptr<EncryptedReportingUploadProvider> GetDefaultUploadProvider( GetCloudPolicyClientCallback build_cloud_policy_client_cb); // Cloud policy client (set by constructor, may only be changed for tests). GetCloudPolicyClientCallback build_cloud_policy_client_cb_; // Upload provider (if enabled). std::unique_ptr<EncryptedReportingUploadProvider> upload_provider_; }; } // namespace reporting #endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_PUBLIC_REPORT_CLIENT_H_
blueboxd/chromium-legacy
ios/chrome/browser/ui/ntp/new_tab_page_feature.h
<reponame>blueboxd/chromium-legacy // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_NTP_NEW_TAB_PAGE_FEATURE_H_ #define IOS_CHROME_BROWSER_UI_NTP_NEW_TAB_PAGE_FEATURE_H_ #include "base/feature_list.h" // Feature flag to enable showing a live preview for Discover feed when opening // the feed context menu. extern const base::Feature kEnableDiscoverFeedPreview; // Feature flag to enable shorter cache so that more ghost cards appear. extern const base::Feature kEnableDiscoverFeedShorterCache; // Feature flag to enable improving the usage of memory of the NTP. extern const base::Feature kEnableNTPMemoryEnhancement; // Feature flag to enable static resource serving for the Discover feed. extern const base::Feature kEnableDiscoverFeedStaticResourceServing; // Feature flag to enable discofeed endpoint for the Discover feed. extern const base::Feature kEnableDiscoverFeedDiscoFeedEndpoint; // Feature flag to enable static resource serving for the Discover feed. extern const base::Feature kEnableDiscoverFeedStaticResourceServing; // A parameter to indicate whether Reconstructed Templates is enabled for static // resource serving. extern const char kDiscoverFeedSRSReconstructedTemplatesEnabled[]; // A parameter to indicate whether Preload Templates is enabled for static // resource serving. extern const char kDiscoverFeedSRSPreloadTemplatesEnabled[]; // Feature flag to enable the Following feed in the NTP. // Use IsFollowingFeedEnabled() instead of this constant directly. extern const base::Feature kFollowingFeedInNTP; // Whether the Discover feed content preview is shown in the context menu. bool IsDiscoverFeedPreviewEnabled(); // Whether the Discover feed appflows are enabled. bool IsDiscoverFeedAppFlowsEnabled(); // Whether the Discover feed shorter cache is enabled. bool IsDiscoverFeedShorterCacheEnabled(); // Whether the Following Feed is enabled. bool IsFollowingFeedEnabled(); #endif // IOS_CHROME_BROWSER_UI_NTP_NEW_TAB_PAGE_FEATURE_H_
blueboxd/chromium-legacy
components/safe_browsing/content/browser/base_blocking_page.h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SAFE_BROWSING_CONTENT_BROWSER_BASE_BLOCKING_PAGE_H_ #define COMPONENTS_SAFE_BROWSING_CONTENT_BROWSER_BASE_BLOCKING_PAGE_H_ #include <map> #include <string> #include <vector> #include "base/macros.h" #include "components/safe_browsing/content/browser/base_ui_manager.h" #include "components/safe_browsing/core/browser/db/v4_protocol_manager_util.h" #include "components/security_interstitials/content/security_interstitial_page.h" #include "components/security_interstitials/core/base_safe_browsing_error_ui.h" #include "components/security_interstitials/core/metrics_helper.h" #include "url/gurl.h" namespace content { class NavigationHandle; } namespace security_interstitials { class SettingsPageHelper; } namespace safe_browsing { // Base class for managing the SafeBrowsing interstitial pages. class BaseBlockingPage : public security_interstitials::SecurityInterstitialPage { public: typedef security_interstitials::UnsafeResource UnsafeResource; typedef security_interstitials::BaseSafeBrowsingErrorUI BaseSafeBrowsingErrorUI; typedef std::vector<UnsafeResource> UnsafeResourceList; typedef std::unordered_map<content::WebContents*, UnsafeResourceList> UnsafeResourceMap; BaseBlockingPage(const BaseBlockingPage&) = delete; BaseBlockingPage& operator=(const BaseBlockingPage&) = delete; ~BaseBlockingPage() override; static const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions CreateDefaultDisplayOptions(const UnsafeResourceList& unsafe_resources); // Returns true if the passed |unsafe_resources| is blocking the load of // the main page. static bool IsMainPageLoadBlocked(const UnsafeResourceList& unsafe_resources); // SecurityInterstitialPage method: void CommandReceived(const std::string& command) override; // Checks the threat type to decide if we should report ThreatDetails. static bool ShouldReportThreatDetails(SBThreatType threat_type); // Populates the report details for |unsafe_resources|. static security_interstitials::MetricsHelper::ReportDetails GetReportingInfo( const UnsafeResourceList& unsafe_resources); // Can be used by implementations of SafeBrowsingBlockingPageFactory. static std::unique_ptr< security_interstitials::SecurityInterstitialControllerClient> CreateControllerClient( content::WebContents* web_contents, const UnsafeResourceList& unsafe_resources, BaseUIManager* ui_manager, PrefService* pref_service, std::unique_ptr<security_interstitials::SettingsPageHelper> settings_page_helper); // If `this` was created for a post commit error page, // `error_page_navigation_handle` is the navigation created for this blocking // page. virtual void CreatedPostCommitErrorPageNavigation( content::NavigationHandle* error_page_navigation_handle) {} protected: // Don't instantiate this class directly, use ShowBlockingPage instead. BaseBlockingPage( BaseUIManager* ui_manager, content::WebContents* web_contents, const GURL& main_frame_url, const UnsafeResourceList& unsafe_resources, std::unique_ptr< security_interstitials::SecurityInterstitialControllerClient> controller_client, const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions& display_options); // SecurityInterstitialPage methods: void PopulateInterstitialStrings(base::Value* load_time_data) override; void OnInterstitialClosing() override {} // Called when the interstitial is going away. Intentionally do nothing in // this base class. virtual void FinishThreatDetails(const base::TimeDelta& delay, bool did_proceed, int num_visits); // A list of SafeBrowsingUIManager::UnsafeResource for a tab that the user // should be warned about. They are queued when displaying more than one // interstitial at a time. static UnsafeResourceMap* GetUnsafeResourcesMap(); static std::string GetMetricPrefix( const UnsafeResourceList& unsafe_resources, BaseSafeBrowsingErrorUI::SBInterstitialReason interstitial_reason); static std::string GetExtraMetricsSuffix( const UnsafeResourceList& unsafe_resources); // Return the most severe interstitial reason from a list of unsafe resources. // Severity ranking: malware > UwS (harmful) > phishing. static BaseSafeBrowsingErrorUI::SBInterstitialReason GetInterstitialReason( const UnsafeResourceList& unsafe_resources); BaseUIManager* ui_manager() const; const GURL main_frame_url() const; UnsafeResourceList unsafe_resources() const; bool proceeded() const; int64_t threat_details_proceed_delay() const; BaseSafeBrowsingErrorUI* sb_error_ui() const; void set_proceeded(bool proceeded); void SetThreatDetailsProceedDelayForTesting(int64_t delay); int GetHTMLTemplateId() override; void set_sb_error_ui(std::unique_ptr<BaseSafeBrowsingErrorUI> sb_error_ui); void OnDontProceedDone(); private: // For reporting back user actions. BaseUIManager* ui_manager_; // The URL of the main frame that caused the warning. GURL main_frame_url_; // The index of a navigation entry that should be removed when DontProceed() // is invoked, -1 if entry should not be removed. const int navigation_entry_index_to_remove_; // The list of unsafe resources this page is warning about. UnsafeResourceList unsafe_resources_; // Indicate whether user has proceeded this blocking page. bool proceeded_; // After a safe browsing interstitial where the user opted-in to the // report but clicked "proceed anyway", we delay the call to // ThreatDetails::FinishCollection() by this much time (in // milliseconds), in order to get data from the blocked resource itself. int64_t threat_details_proceed_delay_ms_; // For displaying safe browsing interstitial. std::unique_ptr<BaseSafeBrowsingErrorUI> sb_error_ui_; }; } // namespace safe_browsing #endif // COMPONENTS_SAFE_BROWSING_CONTENT_BROWSER_BASE_BLOCKING_PAGE_H_
blueboxd/chromium-legacy
media/gpu/vaapi/vaapi_wrapper.h
<gh_stars>10-100 // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This file contains an implementation of VaapiWrapper, used by // VaapiVideoDecodeAccelerator and VaapiH264Decoder for decode, // and VaapiVideoEncodeAccelerator for encode, to interface // with libva (VA-API library for hardware video codec). #ifndef MEDIA_GPU_VAAPI_VAAPI_WRAPPER_H_ #define MEDIA_GPU_VAAPI_VAAPI_WRAPPER_H_ #include <stddef.h> #include <stdint.h> #include <va/va.h> #include <memory> #include <set> #include <vector> #include "base/compiler_specific.h" #include "base/files/file.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" #include "base/synchronization/lock.h" #include "base/thread_annotations.h" #include "build/chromeos_buildflags.h" #include "media/gpu/chromeos/fourcc.h" #include "media/gpu/media_gpu_export.h" #include "media/gpu/vaapi/va_surface.h" #include "media/gpu/vaapi/vaapi_utils.h" #include "media/video/video_decode_accelerator.h" #include "media/video/video_encode_accelerator.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/geometry/size.h" #if BUILDFLAG(USE_VAAPI_X11) #include "ui/gfx/x/xproto.h" // nogncheck #endif // BUILDFLAG(USE_VAAPI_X11) namespace gfx { enum class BufferFormat; class NativePixmap; class NativePixmapDmaBuf; class Rect; } namespace media { constexpr unsigned int kInvalidVaRtFormat = 0u; class VideoFrame; // Enum, function and callback type to allow VaapiWrapper to log errors in VA // function calls executed on behalf of its owner. |histogram_name| is prebound // to allow for disinguishing such owners. enum class VaapiFunctions; void ReportVaapiErrorToUMA(const std::string& histogram_name, VaapiFunctions value); using ReportErrorToUMACB = base::RepeatingCallback<void(VaapiFunctions)>; // This struct holds a NativePixmapDmaBuf, usually the result of exporting a VA // surface, and some associated size information needed to tell clients about // the underlying buffer. struct NativePixmapAndSizeInfo { NativePixmapAndSizeInfo(); ~NativePixmapAndSizeInfo(); // The VA-API internal buffer dimensions, which may be different than the // dimensions requested at the time of creation of the surface (but always // larger than or equal to those). This can be used for validation in, e.g., // testing. gfx::Size va_surface_resolution; // The size of the underlying Buffer Object. A use case for this is when an // image decode is requested and the caller needs to know the size of the // allocated buffer for caching purposes. size_t byte_size = 0u; // Contains the information needed to use the surface in a graphics API, // including the visible size (|pixmap|->GetBufferSize()) which should be no // larger than |va_surface_resolution|. scoped_refptr<gfx::NativePixmapDmaBuf> pixmap; }; enum class VAImplementation { kMesaGallium, kIntelI965, kIntelIHD, kOther, kInvalid, }; // This class handles VA-API calls and ensures proper locking of VA-API calls // to libva, the userspace shim to the HW codec driver. libva is not // thread-safe, so we have to perform locking ourselves. This class is fully // synchronous and its constructor, all of its methods, and its destructor must // be called on the same sequence. These methods may wait on the |va_lock_| // which guards libva calls across all VaapiWrapper instances and other libva // call sites. // // This class is responsible for managing VAAPI connection, contexts and state. // It is also responsible for managing and freeing VABuffers (not VASurfaces), // which are used to queue parameters and slice data to the HW codec, // as well as underlying memory for VASurfaces themselves. class MEDIA_GPU_EXPORT VaapiWrapper : public base::RefCountedThreadSafe<VaapiWrapper> { public: enum CodecMode { kDecode, #if BUILDFLAG(IS_CHROMEOS_ASH) // NOTE: A kDecodeProtected VaapiWrapper is created using the actual video // profile and an extra VAProfileProtected, each with some special added // VAConfigAttribs. Then when CreateProtectedSession() is called, it will // then create a protected session using protected profile & entrypoint // which gets attached to the decoding context (or attached when the // decoding context is created or re-created). This then enables // decrypt + decode support in the driver and encrypted frame data can then // be submitted. kDecodeProtected, // Decrypt + decode to protected surface. #endif kEncodeConstantBitrate, // Encode with Constant Bitrate algorithm. kEncodeConstantQuantizationParameter, // Encode with Constant Quantization // Parameter algorithm. kVideoProcess, kCodecModeMax, }; // This is enum associated with VASurfaceAttribUsageHint. enum class SurfaceUsageHint : int32_t { kGeneric = VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC, kVideoDecoder = VA_SURFACE_ATTRIB_USAGE_HINT_DECODER, kVideoEncoder = VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER, kVideoProcessWrite = VA_SURFACE_ATTRIB_USAGE_HINT_VPP_WRITE, }; using InternalFormats = struct { bool yuv420 : 1; bool yuv420_10 : 1; bool yuv422 : 1; bool yuv444 : 1; }; // Returns the type of the underlying VA-API implementation. static VAImplementation GetImplementationType(); // Return an instance of VaapiWrapper initialized for |va_profile| and // |mode|. |report_error_to_uma_cb| will be called independently from // reporting errors to clients via method return values. static scoped_refptr<VaapiWrapper> Create( CodecMode mode, VAProfile va_profile, EncryptionScheme encryption_scheme, const ReportErrorToUMACB& report_error_to_uma_cb); // Create VaapiWrapper for VideoCodecProfile. It maps VideoCodecProfile // |profile| to VAProfile. // |report_error_to_uma_cb| will be called independently from reporting // errors to clients via method return values. static scoped_refptr<VaapiWrapper> CreateForVideoCodec( CodecMode mode, VideoCodecProfile profile, EncryptionScheme encryption_scheme, const ReportErrorToUMACB& report_error_to_uma_cb); VaapiWrapper(const VaapiWrapper&) = delete; VaapiWrapper& operator=(const VaapiWrapper&) = delete; // Returns the supported SVC scalability modes for specified profile. static std::vector<SVCScalabilityMode> GetSupportedScalabilityModes( VideoCodecProfile media_profile, VAProfile va_profile); // Return the supported video encode profiles. static VideoEncodeAccelerator::SupportedProfiles GetSupportedEncodeProfiles(); // Return the supported video decode profiles. static VideoDecodeAccelerator::SupportedProfiles GetSupportedDecodeProfiles(); // Return true when decoding using |va_profile| is supported. static bool IsDecodeSupported(VAProfile va_profile); // Returns the supported internal formats for decoding using |va_profile|. If // decoding is not supported for that profile, returns InternalFormats{}. static InternalFormats GetDecodeSupportedInternalFormats( VAProfile va_profile); // Returns true if |rt_format| is supported for decoding using |va_profile|. // Returns false if |rt_format| or |va_profile| is not supported for decoding. static bool IsDecodingSupportedForInternalFormat(VAProfile va_profile, unsigned int rt_format); // Gets the minimum surface size allowed for decoding using |va_profile|. // Returns true if the size can be obtained, false otherwise. The minimum // dimension (width or height) returned is 1. Particularly, if a dimension is // not reported by the driver, the dimension is returned as 1. static bool GetDecodeMinResolution(VAProfile va_profile, gfx::Size* min_size); // Gets the maximum surface size allowed for decoding using |va_profile|. // Returns true if the size can be obtained, false otherwise. Because of the // initialization in VASupportedProfiles::FillProfileInfo_Locked(), the size // is guaranteed to not be empty (as long as this method returns true). static bool GetDecodeMaxResolution(VAProfile va_profile, gfx::Size* max_size); // Obtains a suitable FOURCC that can be used in vaCreateImage() + // vaGetImage(). |rt_format| corresponds to the JPEG's subsampling format. // |preferred_fourcc| is the FOURCC of the format preferred by the caller. If // it is determined that the VAAPI driver can do the conversion from the // internal format (|rt_format|), *|suitable_fourcc| is set to // |preferred_fourcc|. Otherwise, it is set to a supported format. Returns // true if a suitable FOURCC could be determined, false otherwise (e.g., if // the |rt_format| is unsupported by the driver). If |preferred_fourcc| is not // a supported image format, *|suitable_fourcc| is set to VA_FOURCC_I420. static bool GetJpegDecodeSuitableImageFourCC(unsigned int rt_format, uint32_t preferred_fourcc, uint32_t* suitable_fourcc); // Checks the surface size is allowed for VPP. Returns true if the size is // supported, false otherwise. static bool IsVppResolutionAllowed(const gfx::Size& size); // Returns true if the VPP supports converting from/to |fourcc|. static bool IsVppFormatSupported(uint32_t fourcc); // Returns the pixel formats supported by the VPP. static std::vector<Fourcc> GetVppSupportedFormats(); // Returns true if VPP supports the format conversion from a JPEG decoded // internal surface to a FOURCC. |rt_format| corresponds to the JPEG's // subsampling format. |fourcc| is the output surface's FOURCC. static bool IsVppSupportedForJpegDecodedSurfaceToFourCC( unsigned int rt_format, uint32_t fourcc); // Return true when JPEG encode is supported. static bool IsJpegEncodeSupported(); // Return true when the specified image format is supported. static bool IsImageFormatSupported(const VAImageFormat& format); // Returns the list of VAImageFormats supported by the driver. static const std::vector<VAImageFormat>& GetSupportedImageFormatsForTesting(); // Returns the list of supported profiles and entrypoints for a given |mode|. static std::map<VAProfile, std::vector<VAEntrypoint>> GetSupportedConfigurationsForCodecModeForTesting(CodecMode mode); static VAEntrypoint GetDefaultVaEntryPoint(CodecMode mode, VAProfile profile); static uint32_t BufferFormatToVARTFormat(gfx::BufferFormat fmt); // Creates |num_surfaces| VASurfaceIDs of |va_format|, |size| and // |surface_usage_hints| and, if successful, creates a |va_context_id_| of the // same size. |surface_usage_hints| may affect an alignment and tiling of the // created surface. Returns true if successful, with the created IDs in // |va_surfaces|. The client is responsible for destroying |va_surfaces| via // DestroyContextAndSurfaces() to free the allocated surfaces. virtual bool CreateContextAndSurfaces( unsigned int va_format, const gfx::Size& size, const std::vector<SurfaceUsageHint>& surface_usage_hints, size_t num_surfaces, std::vector<VASurfaceID>* va_surfaces) WARN_UNUSED_RESULT; // Creates |num_surfaces| ScopedVASurfaces of |va_format| and |size| and, if // successful, creates a |va_context_id_| of the same size. Returns an empty // vector if creation failed. If |visible_size| is supplied, the returned // ScopedVASurface's size is set to it. Otherwise, it's set to |size| (refer // to CreateScopedVASurfaces() for details). virtual std::vector<std::unique_ptr<ScopedVASurface>> CreateContextAndScopedVASurfaces( unsigned int va_format, const gfx::Size& size, const std::vector<SurfaceUsageHint>& usage_hints, size_t num_surfaces, const absl::optional<gfx::Size>& visible_size); // Attempts to create a protected session that will be attached to the // decoding context to enable encrypted video decoding. If it cannot be // attached now, it will be attached when the decoding context is created or // re-created. |encryption| should be the encryption scheme from the // DecryptConfig. |hw_config| should have been obtained from the OEMCrypto // implementation via the CdmFactoryDaemonProxy. |hw_identifier_out| is an // output parameter which will return session specific information which can // be passed through the ChromeOsCdmContext to retrieve encrypted key // information. Returns true on success and false otherwise. bool CreateProtectedSession(media::EncryptionScheme encryption, const std::vector<uint8_t>& hw_config, std::vector<uint8_t>* hw_identifier_out); // Returns true if and only if we have created a protected session and // querying libva indicates that our protected session is no longer alive, // otherwise this will return false. bool IsProtectedSessionDead(); #if BUILDFLAG(IS_CHROMEOS_ASH) // Returns true if and only if |va_protected_session_id| is not VA_INVALID_ID // and querying libva indicates that the protected session identified by // |va_protected_session_id| is no longer alive. bool IsProtectedSessionDead(VAProtectedSessionID va_protected_session_id); // Returns the ID of the current protected session or VA_INVALID_ID if there's // none. This must be called on the same sequence as other methods that use // the protected session ID internally. // // TODO(b/183515581): update this documentation once we force the VaapiWrapper // to be used on a single sequence. VAProtectedSessionID GetProtectedSessionID() const; #endif // If we have a protected session, destroys it immediately. This should be // used as part of recovering dead protected sessions. void DestroyProtectedSession(); // Releases the |va_surfaces| and destroys |va_context_id_|. void DestroyContextAndSurfaces(std::vector<VASurfaceID> va_surfaces); // Creates a VAContextID of |size| (unless it's a Vpp context in which case // |size| is ignored and 0x0 is used instead). The client is responsible for // releasing said context via DestroyContext() or DestroyContextAndSurfaces(), // or it will be released on dtor. If a valid |va_protected_session_id_| // exists, it will be attached to the newly created |va_context_id_| as well. virtual bool CreateContext(const gfx::Size& size) WARN_UNUSED_RESULT; // Destroys the context identified by |va_context_id_|. virtual void DestroyContext(); // Requests |num_surfaces| ScopedVASurfaces of size |size|, |va_rt_format| and // optionally |va_fourcc|. Returns self-cleaning ScopedVASurfaces or empty // vector if creation failed. If |visible_size| is supplied, the returned // ScopedVASurfaces' size are set to it: for example, we may want to request a // 16x16 surface to decode a 13x12 JPEG: we may want to keep track of the // visible size 13x12 inside the ScopedVASurface to inform the surface's users // that that's the only region with meaningful content. If |visible_size| is // not supplied, we store |size| in the returned ScopedVASurfaces. virtual std::vector<std::unique_ptr<ScopedVASurface>> CreateScopedVASurfaces( unsigned int va_rt_format, const gfx::Size& size, const std::vector<SurfaceUsageHint>& usage_hints, size_t num_surfaces, const absl::optional<gfx::Size>& visible_size, const absl::optional<uint32_t>& va_fourcc); // Creates a self-releasing VASurface from |pixmap|. The created VASurface // shares the ownership of the underlying buffer represented by |pixmap|. The // ownership of the surface is transferred to the caller. A caller can destroy // |pixmap| after this method returns and the underlying buffer will be kept // alive by the VASurface. |protected_content| should only be true if the // format needs VA_RT_FORMAT_PROTECTED (currently only true for AMD). virtual scoped_refptr<VASurface> CreateVASurfaceForPixmap( scoped_refptr<gfx::NativePixmap> pixmap, bool protected_content = false); // Creates a self-releasing VASurface from |buffers|. The ownership of the // surface is transferred to the caller. |buffers| should be a pointer array // of size 1, with |buffer_size| corresponding to its size. |size| should be // the desired surface dimensions (which does not need to map to |buffer_size| // in any relevant way). |buffers| should be kept alive when using the // VASurface and for accessing the data after the operation is complete. scoped_refptr<VASurface> CreateVASurfaceForUserPtr(const gfx::Size& size, uintptr_t* buffers, size_t buffer_size); // Syncs and exports |va_surface| as a gfx::NativePixmapDmaBuf. Currently, the // only VAAPI surface pixel formats supported are VA_FOURCC_IMC3 and // VA_FOURCC_NV12. // // Notes: // // - For VA_FOURCC_IMC3, the format of the returned NativePixmapDmaBuf is // gfx::BufferFormat::YVU_420 because we don't have a YUV_420 format. The // planes are flipped accordingly, i.e., // gfx::NativePixmapDmaBuf::GetDmaBufOffset(1) refers to the V plane. // TODO(andrescj): revisit once crrev.com/c/1573718 lands. // // - For VA_FOURCC_NV12, the format of the returned NativePixmapDmaBuf is // gfx::BufferFormat::YUV_420_BIPLANAR. // // Returns nullptr on failure. std::unique_ptr<NativePixmapAndSizeInfo> ExportVASurfaceAsNativePixmapDmaBuf( const ScopedVASurface& va_surface); // Synchronize the VASurface explicitly. This is useful when sharing a surface // between contexts. bool SyncSurface(VASurfaceID va_surface_id) WARN_UNUSED_RESULT; // Calls SubmitBuffer_Locked() to request libva to allocate a new VABufferID // of |va_buffer_type| and |size|, and to map-and-copy the |data| into it. The // allocated VABufferIDs stay alive until DestroyPendingBuffers_Locked(). Note // that this method does not submit the buffers for execution, they are simply // stored until ExecuteAndDestroyPendingBuffers()/Execute_Locked(). The // ownership of |data| stays with the caller. On failure, all pending buffers // are destroyed. bool SubmitBuffer(VABufferType va_buffer_type, size_t size, const void* data) WARN_UNUSED_RESULT; // Convenient templatized version of SubmitBuffer() where |size| is deduced to // be the size of the type of |*data|. template <typename T> bool WARN_UNUSED_RESULT SubmitBuffer(VABufferType va_buffer_type, const T* data) { CHECK(sequence_checker_.CalledOnValidSequence()); return SubmitBuffer(va_buffer_type, sizeof(T), data); } // Batch-version of SubmitBuffer(), where the lock for accessing libva is // acquired only once. struct VABufferDescriptor { VABufferType type; size_t size; const void* data; }; bool SubmitBuffers(const std::vector<VABufferDescriptor>& va_buffers) WARN_UNUSED_RESULT; // Destroys all |pending_va_buffers_| sent via SubmitBuffer*(). Useful when a // pending job is to be cancelled (on reset or error). void DestroyPendingBuffers(); // Executes job in hardware on target |va_surface_id| and destroys pending // buffers. Returns false if Execute() fails. virtual bool ExecuteAndDestroyPendingBuffers(VASurfaceID va_surface_id) WARN_UNUSED_RESULT; // Maps each |va_buffers| ID and copies the data described by the associated // VABufferDescriptor into it; then calls Execute_Locked() on |va_surface_id|. bool MapAndCopyAndExecute( VASurfaceID va_surface_id, const std::vector<std::pair<VABufferID, VABufferDescriptor>>& va_buffers) WARN_UNUSED_RESULT; #if BUILDFLAG(USE_VAAPI_X11) // Put data from |va_surface_id| into |x_pixmap| of size // |dest_size|, converting/scaling to it. bool PutSurfaceIntoPixmap(VASurfaceID va_surface_id, x11::Pixmap x_pixmap, gfx::Size dest_size) WARN_UNUSED_RESULT; #endif // BUILDFLAG(USE_VAAPI_X11) // Creates a ScopedVAImage from a VASurface |va_surface_id| and map it into // memory with the given |format| and |size|. If |format| is not equal to the // internal format, the underlying implementation will do format conversion if // supported. |size| should be smaller than or equal to the surface. If |size| // is smaller, the image will be cropped. std::unique_ptr<ScopedVAImage> CreateVaImage(VASurfaceID va_surface_id, VAImageFormat* format, const gfx::Size& size); // Uploads contents of |frame| into |va_surface_id| for encode. virtual bool UploadVideoFrameToSurface(const VideoFrame& frame, VASurfaceID va_surface_id, const gfx::Size& va_surface_size) WARN_UNUSED_RESULT; // Creates a buffer of |size| bytes to be used as encode output. virtual std::unique_ptr<ScopedVABuffer> CreateVABuffer(VABufferType type, size_t size); // Gets the encoded frame linear size of the buffer with given |buffer_id|. // |sync_surface_id| will be used as a sync point, i.e. it will have to become // idle before starting the acquirement. |sync_surface_id| should be the // source surface passed to the encode job. Returns 0 if it fails for any // reason. virtual uint64_t GetEncodedChunkSize(VABufferID buffer_id, VASurfaceID sync_surface_id) WARN_UNUSED_RESULT; // Downloads the contents of the buffer with given |buffer_id| into a buffer // of size |target_size|, pointed to by |target_ptr|. The number of bytes // downloaded will be returned in |coded_data_size|. |sync_surface_id| will // be used as a sync point, i.e. it will have to become idle before starting // the download. |sync_surface_id| should be the source surface passed // to the encode job. Returns false if it fails for any reason. For example, // the linear size of the resulted encoded frame is larger than |target_size|. virtual bool DownloadFromVABuffer(VABufferID buffer_id, VASurfaceID sync_surface_id, uint8_t* target_ptr, size_t target_size, size_t* coded_data_size) WARN_UNUSED_RESULT; // Get the max number of reference frames for encoding supported by the // driver. // For H.264 encoding, the value represents the maximum number of reference // frames for both the reference picture list 0 (bottom 16 bits) and the // reference picture list 1 (top 16 bits). virtual bool GetVAEncMaxNumOfRefFrames(VideoCodecProfile profile, size_t* max_ref_frames) WARN_UNUSED_RESULT; // Gets packed headers are supported for encoding. This is called for // H264 encoding. |packed_sps|, |packed_pps| and |packed_slice| stands for // whether packed slice parameter set, packed picture parameter set and packed // slice header is supported, respectively. virtual bool GetSupportedPackedHeaders(VideoCodecProfile profile, bool& packed_sps, bool& packed_pps, bool& packed_slice) WARN_UNUSED_RESULT; // Checks if the driver supports frame rotation. bool IsRotationSupported(); // Blits a VASurface |va_surface_src| into another VASurface // |va_surface_dest| applying pixel format conversion, rotation, cropping // and scaling if needed. |src_rect| and |dest_rect| are optional. They can // be used to specify the area used in the blit. If |va_protected_session_id| // is provided and is not VA_INVALID_ID, the corresponding protected session // is attached to the VPP context prior to submitting the VPP buffers and // detached after submitting those buffers. virtual bool BlitSurface( const VASurface& va_surface_src, const VASurface& va_surface_dest, absl::optional<gfx::Rect> src_rect = absl::nullopt, absl::optional<gfx::Rect> dest_rect = absl::nullopt, VideoRotation rotation = VIDEO_ROTATION_0 #if BUILDFLAG(IS_CHROMEOS_ASH) , VAProtectedSessionID va_protected_session_id = VA_INVALID_ID #endif ) WARN_UNUSED_RESULT; // Initialize static data before sandbox is enabled. static void PreSandboxInitialization(); // vaDestroySurfaces() a vector or a single VASurfaceID. virtual void DestroySurfaces(std::vector<VASurfaceID> va_surfaces); virtual void DestroySurface(VASurfaceID va_surface_id); protected: VaapiWrapper(CodecMode mode); virtual ~VaapiWrapper(); private: friend class base::RefCountedThreadSafe<VaapiWrapper>; friend class VaapiWrapperTest; friend class VaapiVideoEncodeAcceleratorTest; FRIEND_TEST_ALL_PREFIXES(VaapiTest, LowQualityEncodingSetting); FRIEND_TEST_ALL_PREFIXES(VaapiUtilsTest, ScopedVAImage); FRIEND_TEST_ALL_PREFIXES(VaapiUtilsTest, BadScopedVAImage); FRIEND_TEST_ALL_PREFIXES(VaapiUtilsTest, BadScopedVABufferMapping); FRIEND_TEST_ALL_PREFIXES(VaapiMinigbmTest, AllocateAndCompareWithMinigbm); bool Initialize(VAProfile va_profile, EncryptionScheme encryption_scheme) WARN_UNUSED_RESULT; void Deinitialize(); bool VaInitialize(const ReportErrorToUMACB& report_error_to_uma_cb) WARN_UNUSED_RESULT; // Tries to allocate |num_surfaces| VASurfaceIDs of |size| and |va_format|. // Fills |va_surfaces| and returns true if successful, or returns false. bool CreateSurfaces(unsigned int va_format, const gfx::Size& size, const std::vector<SurfaceUsageHint>& usage_hints, size_t num_surfaces, std::vector<VASurfaceID>* va_surfaces) WARN_UNUSED_RESULT; // Carries out the vaBeginPicture()-vaRenderPicture()-vaEndPicture() on target // |va_surface_id|. Returns false if any of these calls fails. bool Execute_Locked(VASurfaceID va_surface_id, const std::vector<VABufferID>& va_buffers) EXCLUSIVE_LOCKS_REQUIRED(va_lock_) WARN_UNUSED_RESULT; virtual void DestroyPendingBuffers_Locked() EXCLUSIVE_LOCKS_REQUIRED(va_lock_); // Requests libva to allocate a new VABufferID of type |va_buffer.type|, then // maps-and-copies |va_buffer.size| contents of |va_buffer.data| to it. If a // failure occurs, calls DestroyPendingBuffers_Locked() and returns false. virtual bool SubmitBuffer_Locked(const VABufferDescriptor& va_buffer) EXCLUSIVE_LOCKS_REQUIRED(va_lock_) WARN_UNUSED_RESULT; // Maps |va_buffer_id| and, if successful, copies the contents of |va_buffer| // into it. bool MapAndCopy_Locked(VABufferID va_buffer_id, const VABufferDescriptor& va_buffer) EXCLUSIVE_LOCKS_REQUIRED(va_lock_) WARN_UNUSED_RESULT; // Queries whether |va_profile_| and |va_entrypoint_| support encoding quality // setting and, if available, configures it to its maximum value, for lower // consumption and maximum speed. void MaybeSetLowQualityEncoding_Locked() EXCLUSIVE_LOCKS_REQUIRED(va_lock_); // If a protected session is active, attaches it to the decoding context. bool MaybeAttachProtectedSession_Locked() EXCLUSIVE_LOCKS_REQUIRED(va_lock_) WARN_UNUSED_RESULT; const CodecMode mode_; base::SequenceCheckerImpl sequence_checker_; // Pointer to VADisplayState's member |va_lock_|. Guaranteed to be valid for // the lifetime of VaapiWrapper. base::Lock* va_lock_; // VA handles. // All valid after successful Initialize() and until Deinitialize(). VADisplay va_display_ GUARDED_BY(va_lock_); VAConfigID va_config_id_{VA_INVALID_ID}; // Created in CreateContext() or CreateContextAndSurfaces() and valid until // DestroyContext() or DestroyContextAndSurfaces(). VAContextID va_context_id_{VA_INVALID_ID}; // Profile and entrypoint configured for the corresponding |va_context_id_|. VAProfile va_profile_; VAEntrypoint va_entrypoint_; // Data queued up for HW codec, to be committed on next execution. // TODO(b/166646505): let callers manage the lifetime of these buffers. std::vector<VABufferID> pending_va_buffers_; // VA buffer to be used for kVideoProcess. Allocated the first time around, // and reused afterwards. std::unique_ptr<ScopedVABuffer> va_buffer_for_vpp_; #if BUILDFLAG(IS_CHROMEOS_ASH) // For protected decode mode. VAConfigID va_protected_config_id_{VA_INVALID_ID}; VAProtectedSessionID va_protected_session_id_{VA_INVALID_ID}; #endif // Called to report codec errors to UMA. Errors to clients are reported via // return values from public methods. ReportErrorToUMACB report_error_to_uma_cb_; }; } // namespace media #endif // MEDIA_GPU_VAAPI_VAAPI_WRAPPER_H_
blueboxd/chromium-legacy
ash/constants/ash_features.h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_CONSTANTS_ASH_FEATURES_H_ #define ASH_CONSTANTS_ASH_FEATURES_H_ #include "base/component_export.h" #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" namespace ash { namespace features { // All features in alphabetical order. The features should be documented // alongside the definition of their values in the .cc file. If a feature is // being rolled out via Finch, add a comment in the .cc file. COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAdjustSplitViewForVK; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAllowAmbientEQ; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAllowRepeatedUpdates; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAllowScrollSettings; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAmbientModeFeature; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeCapturedOnPixelAlbumEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeCapturedOnPixelPhotosEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeCulturalInstitutePhotosEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeDefaultFeedEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeEarthAndSpaceAlbumEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeFeaturedPhotoAlbumEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeFeaturedPhotosEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeFineArtAlbumEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeGeoPhotosEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModePersonalPhotosEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeRssPhotosEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::FeatureParam<bool> kAmbientModeStreetArtAlbumEnabled; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAmbientModeDevUseProdFeature; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAmbientModePhotoPreviewFeature; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAmbientModeNewUrl; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kArcAdbSideloadingFeature; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kArcInputOverlay; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kArcManagedAdbSideloadingSupport; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistAutoCorrect; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistEmojiEnhanced; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistMultiWord; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistMultiWordExpanded; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistPersonalInfo; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistPersonalInfoAddress; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistPersonalInfoEmail; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistPersonalInfoName; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAssistPersonalInfoPhoneNumber; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAudioUrl; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAutoNightLight; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kAutoScreenBrightness; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kBentoBar; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kBluetoothAdvertisementMonitoring; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kBluetoothFixA2dpPacketSize; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kBluetoothPhoneFilter; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kBluetoothRevamp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kBluetoothWbsDogfood; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kBorealisDiskManagement; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kButtonARCNetworkDiagnostics; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCalendarView; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCameraPrivacySwitchNotifications; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCellularAllowPerNetworkRoaming; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCellularForbidAttachApn; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCellularUseAttachApn; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCellularUseExternalEuicc; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kClipboardHistory; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kClipboardHistoryContextMenuNudge; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kClipboardHistoryNudgeSessionReset; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kClipboardHistoryScreenshotNudge; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCompositingBasedThrottling; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kContextualNudges; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCroshSWA; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCrostiniBullseyeUpgrade; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCrostiniUseDlc; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDesksTemplates; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDiagnosticsApp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCrostiniDiskResizing; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCrostiniGpuSupport; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCrostiniResetLxdDb; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCrostiniUseLxd4; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCrostiniMultiContainer; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCryptAuthV2DeviceActivityStatus; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCryptAuthV2DeviceActivityStatusUseConnectivity; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCryptAuthV2DeviceSync; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kCryptAuthV2Enrollment; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDarkLightMode; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDemoModeSWA; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDeskTemplateSync; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDeviceActiveClient; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDiagnosticsApp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDiagnosticsAppNavigation; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDisableCryptAuthV1DeviceSync; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDisableIdleSocketsCloseOnMemoryPressure; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDisableOfficeEditingComponentApp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDisplayAlignAssist; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDockedMagnifier; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDragUnpinnedAppToPin; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDragWindowToNewDesk; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDriveFs; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDriveFsBidirectionalNativeMessaging; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDriveFsMirroring; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEcheSWA; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEcheSWAResizing; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEcheSWADebugMode; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEmojiSuggestAddition; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableBackgroundBlur; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableDesksTrackpadSwipeImprovements; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableDnsProxy; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableFilesAppCopyImage; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableHostnameSetting; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableIdleInhibit; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableInputInDiagnosticsApp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableInputNoiseCancellationUi; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableLazyLoginWebUILoading; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableLocalSearchService; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableNetworkingInDiagnosticsApp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableOAuthIpp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableOobeChromeVoxHint; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableOobePolymer3; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnablePciguardUi; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableSamlNotificationOnPasswordChangeSuccess; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableSamlReauthenticationOnLockscreen; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEnableWireGuard; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kEolWarningNotifications; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kESimPolicy; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kExoLockNotification; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kExoOrdinalMotion; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kExoPointerLock; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFamilyLinkOnSchoolDevice; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFastPair; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFilesArchivemount; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFilesBannerFramework; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFilesSWA; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFilesSinglePartitionFormat; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFilesTrash; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFilesZipUnpack; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFiltersInRecents; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFirmwareUpdaterApp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFullscreenAlertBubble; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kFuseBox; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kGaiaCloseViewMessage; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kGaiaReauthEndpoint; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kGamepadVibration; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kGesturePropertiesDBusService; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHandwritingGestureEditing; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHandwritingLegacyRecognition; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHelpAppBackgroundPage; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHelpAppDiscoverTab; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHelpAppDiscoverTabNotificationAllChannels; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHelpAppLauncherSearch; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHelpAppSearchServiceIntegration; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHiddenNetworkWarning; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHideArcMediaNotifications; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHideShelfControlsInTabletMode; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHoldingSpaceInProgressDownloadsIntegration; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHoldingSpaceIncognitoProfileIntegration; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kHpsNotify; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kImeMojoDecoder; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kImeMozcProto; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kImeOptionsInSettings; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kImeSystemEmojiPicker; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kImeSystemEmojiPickerClipboard; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kImeStylusHandwriting; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kImprovedScreenCaptureSettings; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kInstantTethering; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kKeyboardBasedDisplayArrangementInSettings; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLacrosPrimary; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLacrosSupport; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLanguagePacksHandwriting; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLanguageSettingsUpdate2; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLauncherAppSort; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLauncherNudgeShortInterval; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLicensePackagedOobeFlow; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLockScreenHideSensitiveNotificationsSupport; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLockScreenInlineReply; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLockScreenNotifications; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kLockScreenMediaControls; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kManagedDeviceUIRedesign; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kMediaAppHandlesAudio; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kMediaAppHandlesPdf; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kManagedTermsOfService; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kMicMuteNotifications; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kMinimumChromeVersion; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kMojoDBusRelay; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kMultilingualTyping; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNearbyKeepAliveFix; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNewLockScreenReauthLayout; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNightLight; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kMinorModeRestriction; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNoteTakingForEnabledWebApps; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNotificationExpansionAnimation; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNotificationExperimentalShortTimeouts; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNotificationScrollBar; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNotificationsInContextMenu; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kNotificationsRefresh; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kOnDeviceGrammarCheck; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kOnDeviceSpeechRecognition; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kOsFeedback; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kOobeConsolidatedConsent; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kOsSettingsAppNotificationsPage; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kOverviewButton; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPcieBillboardNotification; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPerDeskShelf; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPerUserMetrics; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPerformantSplitViewResizing; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPhoneHub; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPhoneHubCameraRoll; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPhoneHubCallNotification; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPhoneHubRecentApps; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPinSetupForManagedUsers; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPipRoundedCorners; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kPreferConstantFrameRate; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kProductivityLauncher; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kProjector; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kProjectorFeaturePod; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kProjectorAnnotator; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kDisableQuickAnswersV2Translation; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kQuickAnswersV2SettingsSubToggle; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kQuickSettingsNetworkRevamp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kQuickUnlockFingerprint; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kQuickUnlockPinAutosubmit; // TODO(crbug.com/1104164) - Remove this once most users have their preferences // backfilled. COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kQuickUnlockPinAutosubmitBackfill; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kReduceDisplayNotifications; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kReleaseNotesNotificationAllChannels; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kReleaseNotesSuggestionChip; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kRevenLogSource; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kReverseScrollGestures; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kScalableStatusArea; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kScanAppMediaLink; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kScanAppMultiPageScan; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kScanAppSearchablePdf; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kScanAppStickySettings; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSemanticColorsDebugOverride; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSeparateNetworkIcons; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSessionManagerLongKillTimeout; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSessionManagerLivenessCheck; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSettingsAppNotificationSettings; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kShelfLauncherNudge; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kShimlessRMAFlow; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kShowBluetoothDebugLogToggle; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kShowFeedbackReportQuestionnaire; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kShowPlayInDemoMode; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSmartDimExperimentalComponent; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSmartLockUIRevamp; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kStylusBatteryStatus; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSyncConsentOptional; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSyncSettingsCategorization; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSystemChinesePhysicalTyping; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSystemJapanesePhysicalTyping; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSystemKoreanPhysicalTyping; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSystemLatinPhysicalTyping; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kSystemProxyForSystemServices; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kTabClusterUI; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kTelemetryExtension; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kTerminalSSH; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kTrafficCountersSettingsUi; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kTrilinearFiltering; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kUseBluetoothSystemInAsh; // Visible for testing. Call UseBrowserSyncConsent() to check the flag. COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kUseBrowserSyncConsent; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kUseMessagesStagingUrl; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kUseSearchClickForRightClick; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kUseStorkSmdsServerAddress; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kUseWallpaperStagingUrl; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kUserActivityPrediction; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kVirtualKeyboardApi; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kVirtualKeyboardBorderedKey; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kVirtualKeyboardMultipaste; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kVirtualKeyboardMultipasteSuggestion; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWakeOnWifiAllowed; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWallpaperWebUI; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWallpaperFullScreenPreview; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWallpaperGooglePhotosIntegration; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWebApkGenerator; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWebUITabStripTabDragIntegration; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWifiSyncAllowDeletes; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWifiSyncAndroid; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWifiSyncApplyDeletes; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWindowControlMenu; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kWindowsFollowCursor; // Keep alphabetized. COMPONENT_EXPORT(ASH_CONSTANTS) bool AreContextualNudgesEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool AreDesksTemplatesEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool AreDesksTrackpadSwipeImprovementsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool AreImprovedScreenCaptureSettingsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool DoWindowsFollowCursor(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAdjustSplitViewForVKEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAllowAmbientEQEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAmbientModeDevUseProdEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAmbientModeEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAmbientModePhotoPreviewEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAmbientModeNewUrlEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAppNotificationsPageEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsArcInputOverlayEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsArcNetworkDiagnosticsButtonEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAssistiveMultiWordEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsAutoNightLightEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsBackgroundBlurEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsBentoBarEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsBluetoothAdvertisementMonitoringEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsBluetoothRevampEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsCalendarViewEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsClipboardHistoryContextMenuNudgeEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsClipboardHistoryEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsClipboardHistoryNudgeSessionResetEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsClipboardHistoryScreenshotNudgeEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsCompositingBasedThrottlingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDarkLightModeEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDeepLinkingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDemoModeSWAEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDeskTemplateSyncEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDiagnosticsAppEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDisplayAlignmentAssistanceEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDragUnpinnedAppToPinEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDragWindowToNewDeskEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsEcheSWAEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsEcheSWAResizingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsEcheSWADebugModeEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsESimPolicyEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsFamilyLinkOnSchoolDeviceEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsFastPairEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsFileManagerSwaEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsFirmwareUpdaterAppEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsFullscreenAlertBubbleEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsGaiaCloseViewMessageEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsGaiaReauthEndpointEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHideArcMediaNotificationsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHideShelfControlsInTabletModeEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHoldingSpaceInProgressDownloadsIntegrationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHoldingSpaceIncognitoProfileIntegrationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHostnameSettingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsHpsNotifyEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsIdleInhibitEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsInputInDiagnosticsAppEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsInputNoiseCancellationUiEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsInstantTetheringBackgroundAdvertisingSupported(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsKeyboardBasedDisplayArrangementInSettingsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsLauncherAppSortEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsLauncherNudgeShortIntervalEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsLicensePackagedOobeFlowEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsLockScreenHideSensitiveNotificationsSupported(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsLockScreenInlineReplyEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsLockScreenNotificationsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsManagedDeviceUIRedesignEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsManagedTermsOfServiceEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsMicMuteNotificationsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsMinimumChromeVersionEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsMinorModeRestrictionEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNearbyKeepAliveFixEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNetworkingInDiagnosticsAppEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNewLockScreenReauthLayoutEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNotificationExpansionAnimationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNotificationExperimentalShortTimeoutsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNotificationScrollBarEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNotificationsInContextMenuEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNotificationsRefreshEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOAuthIppEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeChromeVoxHintEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobePolymer3Enabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeConsolidatedConsentEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPcieBillboardNotificationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPciguardUiEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPerDeskShelfEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPhoneHubCameraRollEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPerformantSplitViewResizingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPhoneHubEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPhoneHubCallNotificationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPhoneHubRecentAppsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPinAutosubmitBackfillFeatureEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPinAutosubmitFeatureEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPinSetupForManagedUsersEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsPipRoundedCornersEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsProductivityLauncherEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsProjectorEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsProjectorFeaturePodEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsProjectorAnnotatorEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsQuickAnswersV2Enabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsQuickAnswersV2TranslationDisabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsQuickAnswersV2SettingsSubToggleEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsQuickSettingsNetworkRevampEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsReduceDisplayNotificationsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsReverseScrollGesturesEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSamlNotificationOnPasswordChangeSuccessEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSamlReauthenticationOnLockscreenEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsScalableStatusAreaEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSeparateNetworkIconsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSettingsAppNotificationSettingsEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsShelfLauncherNudgeEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsShimlessRMAFlowEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSyncSettingsCategorizationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSyncConsentOptionalEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsStylusBatteryStatusEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSystemChinesePhysicalTypingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSystemJapanesePhysicalTypingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSystemKoreanPhysicalTypingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsSystemLatinPhysicalTypingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsTabClusterUIEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsTrilinearFilteringEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsUseStorkSmdsServerAddressEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsWallpaperWebUIEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsWallpaperFullScreenPreviewEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsWallpaperGooglePhotosIntegrationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsWebUITabStripTabDragIntegrationEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsWifiSyncAndroidEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsWindowControlMenuEnabled(); // TODO(michaelpg): Remove after M71 branch to re-enable Play Store by default. COMPONENT_EXPORT(ASH_CONSTANTS) bool ShouldShowPlayStoreInDemoMode(); COMPONENT_EXPORT(ASH_CONSTANTS) bool ShouldUseAttachApn(); COMPONENT_EXPORT(ASH_CONSTANTS) bool ShouldUseBrowserSyncConsent(); COMPONENT_EXPORT(ASH_CONSTANTS) bool ShouldUseV1DeviceSync(); COMPONENT_EXPORT(ASH_CONSTANTS) bool ShouldUseV2DeviceSync(); // Keep alphabetized. // These two functions are supposed to be temporary functions to set or get // whether "WebUITabStrip" feature is enabled from Chrome. COMPONENT_EXPORT(ASH_CONSTANTS) void SetWebUITabStripEnabled(bool enabled); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsWebUITabStripEnabled(); } // namespace features } // namespace ash // TODO(https://crbug.com/1164001): remove after //chrome/browser/chromeos // source migration is finished. namespace chromeos { namespace features { using namespace ::ash::features; } } // namespace chromeos #endif // ASH_CONSTANTS_ASH_FEATURES_H_
blueboxd/chromium-legacy
chrome/browser/supervised_user/web_approvals_manager.h
<filename>chrome/browser/supervised_user/web_approvals_manager.h // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SUPERVISED_USER_WEB_APPROVALS_MANAGER_H_ #define CHROME_BROWSER_SUPERVISED_USER_WEB_APPROVALS_MANAGER_H_ #include <stddef.h> #include <memory> #include <vector> #include "base/callback_forward.h" #include "base/memory/weak_ptr.h" class GURL; class PermissionRequestCreator; // Manages remote web approval requests from Family Link users. // Remote requests are forwarded to the guardian and processed asynchronously. // The result of the remote approval is not handled in this class. class WebApprovalsManager { public: using RemoteRequestSent = base::OnceCallback<void(bool)>; WebApprovalsManager(); WebApprovalsManager(const WebApprovalsManager&) = delete; WebApprovalsManager& operator=(const WebApprovalsManager&) = delete; ~WebApprovalsManager(); // Adds a remote approval request for the `url`. // The callback is run when the request was sent or sending of the request // failed. void RequestRemoteApproval(const GURL& url, RemoteRequestSent callback); // Returns whether remote approval requests are enabled. bool AreRemoteApprovalRequestsEnabled() const; // Adds remote approval request `creator` to handle remote approval requests. void AddRemoteApprovalRequestCreator( std::unique_ptr<PermissionRequestCreator> creator); // Clears all remote approval requests creators. void ClearRemoteApprovalRequestsCreators(); private: using CreatePermissionRequestCallback = base::RepeatingCallback<void(PermissionRequestCreator*, RemoteRequestSent)>; size_t FindEnabledApprovalRequestCreator(size_t start) const; void AddPermissionRequestInternal( const CreatePermissionRequestCallback& create_request, RemoteRequestSent callback, size_t index); void OnPermissionRequestIssued( const CreatePermissionRequestCallback& create_request, RemoteRequestSent callback, size_t index, bool success); // Stores remote approval request creators. // The creators are cleared during shutdown. std::vector<std::unique_ptr<PermissionRequestCreator>> remote_approval_request_creators_; base::WeakPtrFactory<WebApprovalsManager> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_SUPERVISED_USER_WEB_APPROVALS_MANAGER_H_
blueboxd/chromium-legacy
ui/accessibility/platform/ax_private_attributes_mac.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_ACCESSIBILITY_PLATFORM_AX_PRIVATE_ATTRIBUTES_MAC_H_ #define UI_ACCESSIBILITY_PLATFORM_AX_PRIVATE_ATTRIBUTES_MAC_H_ #import <Cocoa/Cocoa.h> #include "ui/accessibility/ax_export.h" // Private WebKit accessibility attributes. AX_EXPORT constexpr NSString* const NSAccessibilityAccessKeyAttribute = @"AXAccessKey"; AX_EXPORT constexpr NSString* const NSAccessibilityARIAAtomicAttribute = @"AXARIAAtomic"; AX_EXPORT constexpr NSString* const NSAccessibilityARIABusyAttribute = @"AXARIABusy"; AX_EXPORT constexpr NSString* const NSAccessibilityARIACurrentAttribute = @"AXARIACurrent"; AX_EXPORT constexpr NSString* const NSAccessibilityARIALiveAttribute = @"AXARIALive"; AX_EXPORT constexpr NSString* const NSAccessibilityARIARelevantAttribute = @"AXARIARelevant"; AX_EXPORT constexpr NSString* const NSAccessibilityAutocompleteValueAttribute = @"AXAutocompleteValue"; #endif // UI_ACCESSIBILITY_PLATFORM_AX_PRIVATE_ATTRIBUTES_MAC_H_
blueboxd/chromium-legacy
chrome/browser/enterprise/connectors/device_trust/key_management/installer/key_rotation_manager_impl.h
<reponame>blueboxd/chromium-legacy<filename>chrome/browser/enterprise/connectors/device_trust/key_management/installer/key_rotation_manager_impl.h // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_KEY_MANAGEMENT_INSTALLER_KEY_ROTATION_MANAGER_IMPL_H_ #define CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_KEY_MANAGEMENT_INSTALLER_KEY_ROTATION_MANAGER_IMPL_H_ #include <memory> #include <string> #include "chrome/browser/enterprise/connectors/device_trust/key_management/core/signing_key_pair.h" #include "chrome/browser/enterprise/connectors/device_trust/key_management/installer/key_rotation_manager.h" #include "components/policy/proto/device_management_backend.pb.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace crypto { class UnexportableSigningKey; } // namespace crypto namespace enterprise_connectors { class KeyNetworkDelegate; class KeyPersistenceDelegate; class KeyRotationManagerImpl : public KeyRotationManager { public: using KeyTrustLevel = enterprise_management::BrowserPublicKeyUploadRequest::KeyTrustLevel; KeyRotationManagerImpl( std::unique_ptr<KeyNetworkDelegate> network_delegate, std::unique_ptr<KeyPersistenceDelegate> persistence_delegate); ~KeyRotationManagerImpl() override; // KeyRotationManager: bool RotateWithAdminRights(const GURL& dm_server_url, const std::string& dm_token, const std::string& nonce) override WARN_UNUSED_RESULT; private: // Builds the protobuf message needed to tell DM server about the new public // for this device. `nonce` is an opaque binary blob and should not be // treated as an ASCII or UTF-8 string. bool BuildUploadPublicKeyRequest( KeyTrustLevel new_trust_level, const std::unique_ptr<crypto::UnexportableSigningKey>& new_key_pair, const std::string& nonce, enterprise_management::BrowserPublicKeyUploadRequest* request); std::unique_ptr<KeyNetworkDelegate> network_delegate_; std::unique_ptr<KeyPersistenceDelegate> persistence_delegate_; absl::optional<SigningKeyPair> key_pair_; }; } // namespace enterprise_connectors #endif // CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_KEY_MANAGEMENT_INSTALLER_KEY_ROTATION_MANAGER_IMPL_H_
blueboxd/chromium-legacy
ash/controls/scroll_view_gradient_helper.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_CONTROLS_SCROLL_VIEW_GRADIENT_HELPER_H_ #define ASH_CONTROLS_SCROLL_VIEW_GRADIENT_HELPER_H_ #include <memory> #include "ash/ash_export.h" #include "base/callback_list.h" #include "ui/views/controls/scroll_view.h" namespace ash { class GradientLayerDelegate; // Draws fade in / fade out gradients at the top and bottom of a ScrollView. // Uses layer masks to draw the gradient. Each gradient only shows if the view // can be scrolled in that direction. For efficiency, does not create a layer // mask if no gradient is showing (i.e. if the scroll view contents fit in the // viewport and hence the view cannot be scrolled). // // Views using this helper should call UpdateGradientZone() whenever the scroll // view bounds or contents bounds change (e.g. from Layout()). class ASH_EXPORT ScrollViewGradientHelper { public: // `scroll_view` must have a layer. explicit ScrollViewGradientHelper(views::ScrollView* scroll_view); ~ScrollViewGradientHelper(); // Updates the gradients based on `scroll_view_` bounds and scroll position. void UpdateGradientZone(); GradientLayerDelegate* gradient_layer_for_test() { return gradient_layer_.get(); } private: // The scroll view being decorated. views::ScrollView* const scroll_view_; // Draws the fade in/out gradients via a `scroll_view_` mask layer. std::unique_ptr<GradientLayerDelegate> gradient_layer_; // Callback subscriptions. base::CallbackListSubscription on_contents_scrolled_subscription_; base::CallbackListSubscription on_contents_scroll_ended_subscription_; }; } // namespace ash #endif // ASH_CONTROLS_SCROLL_VIEW_GRADIENT_HELPER_H_
blueboxd/chromium-legacy
chrome/browser/ash/crosapi/browser_data_migrator.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_CROSAPI_BROWSER_DATA_MIGRATOR_H_ #define CHROME_BROWSER_ASH_CROSAPI_BROWSER_DATA_MIGRATOR_H_ #include <atomic> #include <memory> #include <vector> #include "base/callback.h" #include "base/files/file_path.h" #include "base/gtest_prod_util.h" #include "base/strings/string_piece.h" #include "base/synchronization/atomic_flag.h" #include "base/timer/elapsed_timer.h" #include "base/version.h" #include "chrome/browser/ash/crosapi/migration_progress_tracker.h" #include "components/account_id/account_id.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" namespace ash { // User data directory name for lacros. constexpr char kLacrosDir[] = "lacros"; // Profile data directory name for lacros. constexpr char kLacrosProfilePath[] = "Default"; // The name of temporary directory that will store copies of files from the // original user data directory. At the end of the migration, it will be moved // to the appropriate destination. constexpr char kTmpDir[] = "browser_data_migrator"; // The following are UMA names. constexpr char kFinalStatus[] = "Ash.BrowserDataMigrator.FinalStatus"; constexpr char kCopiedDataSize[] = "Ash.BrowserDataMigrator.CopiedDataSizeMB"; constexpr char kNoCopyDataSize[] = "Ash.BrowserDataMigrator.NoCopyDataSizeMB"; constexpr char kAshDataSize[] = "Ash.BrowserDataMigrator.AshDataSizeMB"; constexpr char kLacrosDataSize[] = "Ash.BrowserDataMigrator.LacrosDataSizeMB"; constexpr char kCommonDataSize[] = "Ash.BrowserDataMigrator.CommonDataSizeMB"; constexpr char kTotalTime[] = "Ash.BrowserDataMigrator.TotalTimeTakenMS"; constexpr char kLacrosDataTime[] = "Ash.BrowserDataMigrator.LacrosDataTimeTakenMS"; constexpr char kCommonDataTime[] = "Ash.BrowserDataMigrator.CommonDataTimeTakenMS"; constexpr char kCreateDirectoryFail[] = "Ash.BrowserDataMigrator.CreateDirectoryFailure"; // The following UMAs are recorded from // `BrowserDataMigrator::DryRunToCollectUMA()`. constexpr char kDryRunNoCopyDataSize[] = "Ash.BrowserDataMigrator.DryRunNoCopyDataSizeMB"; constexpr char kDryRunAshDataSize[] = "Ash.BrowserDataMigrator.DryRunAshDataSizeMB"; constexpr char kDryRunLacrosDataSize[] = "Ash.BrowserDataMigrator.DryRunLacrosDataSizeMB"; constexpr char kDryRunCommonDataSize[] = "Ash.BrowserDataMigrator.DryRunCommonDataSizeMB"; constexpr char kDryRunCopyMigrationHasEnoughDiskSpace[] = "Ash.BrowserDataMigrator.DryRunHasEnoughDiskSpace.Copy"; constexpr char kDryRunMoveMigrationHasEnoughDiskSpace[] = "Ash.BrowserDataMigrator.DryRunHasEnoughDiskSpace.Move"; constexpr char kDryRunDeleteAndCopyMigrationHasEnoughDiskSpace[] = "Ash.BrowserDataMigrator.DryRunHasEnoughDiskSpace.DeleteAndCopy"; constexpr char kDryRunDeleteAndMoveMigrationHasEnoughDiskSpace[] = "Ash.BrowserDataMigrator.DryRunHasEnoughDiskSpace.DeleteAndMove"; // Local state pref name, which is used to keep track of what step migration is // at. This ensures that ash does not get repeatedly for migration. // 1. The user logs in and restarts ash if necessary to apply flags. // 2. Migration check runs. // 3. Restart ash to run migration. // 4. Restart ash again to show the home screen. constexpr char kMigrationStep[] = "ash.browser_data_migrator.migration_step"; // CancelFlag class CancelFlag : public base::RefCountedThreadSafe<CancelFlag> { public: CancelFlag(); CancelFlag(const CancelFlag&) = delete; CancelFlag& operator=(const CancelFlag&) = delete; void Set() { cancelled_ = true; } bool IsSet() const { return cancelled_; } private: friend base::RefCountedThreadSafe<CancelFlag>; ~CancelFlag(); std::atomic_bool cancelled_; }; // BrowserDataMigrator is responsible for one time browser data migration from // ash-chrome to lacros-chrome. class BrowserDataMigrator { public: // Used to describe a file/dir that has to be migrated. struct TargetItem { enum class ItemType { kFile, kDirectory }; TargetItem(base::FilePath path, int64_t size, ItemType item_type); ~TargetItem() = default; bool operator==(const TargetItem& rhs) const; base::FilePath path; // The size of the TargetItem. If TargetItem is a directory, it is the sum // of all files under the directory. int64_t size; bool is_directory; }; // Used to describe what files/dirs have to be migrated to the new location // and the total byte size of those files. struct TargetInfo { TargetInfo(); ~TargetInfo(); TargetInfo(TargetInfo&&); // Items that should stay in ash data dir. std::vector<TargetItem> ash_data_items; // Items that should be moved to lacros data dir. std::vector<TargetItem> lacros_data_items; // Items that will be duplicated in both ash and lacros data dir. std::vector<TargetItem> common_data_items; // Items that can be deleted from both ash and lacros data dir. std::vector<TargetItem> no_copy_data_items; // The total size of `ash_data_items`. int64_t ash_data_size; // The total size of items that can be deleted during the migration. int64_t no_copy_data_size; // The total size of `lacros_data_items`. int64_t lacros_data_size; // The total size of `common_data_items`. int64_t common_data_size; // The size of data that are duplicated. Equivalent to the extra space // needed for the migration. Currently this is equal to `lacros_data_size + // common_data_size` since we are copying lacros data rather than moving // them. int64_t TotalCopySize() const; // The total size of the profile data directory. It is the sum of ash, // no_copy, lacros and common sizes. int64_t TotalDirSize() const; }; // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. // // This enum corresponds to BrowserDataMigratorFinalStatus in hisograms.xml // and enums.xml. enum class FinalStatus { kSkipped = 0, // No longer in use. kSuccess = 1, kGetPathFailed = 2, kDeleteTmpDirFailed = 3, kNotEnoughSpace = 4, kCopyFailed = 5, kMoveFailed = 6, kDataWipeFailed = 7, kSizeLimitExceeded = 8, kCancelled = 9, kMaxValue = kCancelled }; // The value for `kMigrationStep`. enum class MigrationStep { kCheckStep = 0, // Migration check should run. kRestartCalled = 1, // `MaybeRestartToMigrate()` called restart. kStarted = 2, // `Migrate()` was called. kEnded = 3 // Migration ended. It was either skipped, failed or succeeded. }; enum class ResultValue { kSkipped, kSucceeded, kFailed, kCancelled }; // Return value of `MigrateInternal()`. struct MigrationResult { // Describes the end result of user data wipe. ResultValue data_wipe; // Describes the end result of data migration. ResultValue data_migration; }; // Specifies the mode of migration. enum class Mode { kCopy = 0, // Copies browser related files to lacros. kMove = 1, // Moves browser related files to lacros while copying files // that are needed by both ash and lacros. kDeleteAndCopy = 2, // Similar to kCopy but deletes // TargetInfo::no_copy_items to make extra space. kDeleteAndMove = 3 // Similar to kMove but deletes // TargetInfo::no_copy_items to make extra space. }; // Checks if migration is required for the user identified by `user_id_hash` // and if it is required, calls a DBus method to session_manager and // terminates ash-chrome. static void MaybeRestartToMigrate(const AccountId& account_id, const std::string& user_id_hash); // The method needs to be called on UI thread. It posts `MigrateInternal()` on // a worker thread and returns a callback which can be used to cancel // migration mid way. `progress_callback` is called to update the progress bar // on the screen. // `completion_callbackchrome/browser/ash/crosapi/browser_data_migrator.cc` // passed as an argument will be called on the original thread once migration // has completed or failed. static base::OnceClosure Migrate(const std::string& user_id_hash, const ProgressCallback& progress_callback, base::OnceClosure completion_callback); // Registers boolean pref `kCheckForMigrationOnRestart` with default as false. static void RegisterLocalStatePrefs(PrefRegistrySimple* registry); // Clears the value of `kMigrationStep` in Local State. static void ClearMigrationStep(PrefService* local_state); // Collects migration specific UMAs without actually running the migration. It // does not check if lacros is enabled. static void DryRunToCollectUMA(const base::FilePath& profile_data_dir); private: FRIEND_TEST_ALL_PREFIXES(BrowserDataMigratorTest, IsMigrationRequiredOnWorker); FRIEND_TEST_ALL_PREFIXES(BrowserDataMigratorTest, GetTargetInfo); FRIEND_TEST_ALL_PREFIXES(BrowserDataMigratorTest, CopyDirectory); FRIEND_TEST_ALL_PREFIXES(BrowserDataMigratorTest, SetupTmpDir); FRIEND_TEST_ALL_PREFIXES(BrowserDataMigratorTest, CancelSetupTmpDir); FRIEND_TEST_ALL_PREFIXES(BrowserDataMigratorTest, RecordStatus); FRIEND_TEST_ALL_PREFIXES(BrowserDataMigratorTest, Migrate); // Gets the value of `kMigrationStep` in Local State. static MigrationStep GetMigrationStep(PrefService* local_state); // Sets the value of `kMigrationStep` in Local State. static void SetMigrationStep(PrefService* local_state, MigrationStep step); // The method includes a blocking operation. It checks if lacros user data dir // already exists or not. Check if lacros is enabled or not beforehand. static bool IsMigrationRequiredOnWorker(base::FilePath user_data_dir, const std::string& user_id_hash); // Handles the migration on a worker thread. Returns the end status of data // wipe and migration. `progress_callback` gets posted on UI thread whenever // an update to the UI is required static MigrationResult MigrateInternal( const base::FilePath& original_user_dir, std::unique_ptr<MigrationProgressTracker> progress_tracker, scoped_refptr<CancelFlag> cancel_flag); // This will be posted with `IsMigrationRequiredOnWorker()` as the reply on UI // thread or called directly from `MaybeRestartToMigrate()`. static void MaybeRestartToMigrateCallback(const AccountId& account_id, bool is_required); // Called on UI thread once migration is finished. static void MigrateInternalFinishedUIThread(base::OnceClosure callback, const std::string& user_id_hash, MigrationResult result); // Records to UMA histograms. Note that if `target_info` is nullptr, timer // will be ignored. static void RecordStatus(const FinalStatus& final_status, const TargetInfo* target_info = nullptr, const base::ElapsedTimer* timer = nullptr); // Create `TargetInfo` from `original_user_dir`. `TargetInfo` will include // paths of files/dirs that needs to be migrated. static TargetInfo GetTargetInfo(const base::FilePath& original_user_dir); // Compares space available for `to_dir` against total byte size that // needs to be copied. static bool HasEnoughDiskSpace(const TargetInfo& target_info, const base::FilePath& original_user_dir, Mode mode); // TODO(crbug.com/1248318):Remove this arbitrary cap for migration once a long // term solution is found. Temporarily limit the migration size to 4GB until // the slow migration speed issue is resolved. static bool IsMigrationSmallEnough(const TargetInfo& target_info); // Set up the temporary directory `tmp_dir` by copying items into it. static bool SetupTmpDir(const TargetInfo& target_info, const base::FilePath& from_dir, const base::FilePath& tmp_dir, CancelFlag* cancel_flag, MigrationProgressTracker* progress_tracker); // Copies `items` to `to_dir`. `items_size` and `category_name` are used for // logging. static bool CopyTargetItems(const base::FilePath& to_dir, const std::vector<TargetItem>& items, CancelFlag* cancel_flag, int64_t items_size, base::StringPiece category_name, MigrationProgressTracker* progress_tracker); // Copies `item` to location pointed by `dest`. Returns true on success and // false on failure. static bool CopyTargetItem(const BrowserDataMigrator::TargetItem& item, const base::FilePath& dest, CancelFlag* cancel_flag, MigrationProgressTracker* progress_tracker); // Copies the contents of `from_path` to `to_path` recursively. Unlike // `base::CopyDirectory()` it skips symlinks. static bool CopyDirectory(const base::FilePath& from_path, const base::FilePath& to_path, CancelFlag* cancel_flag, MigrationProgressTracker* progress_tracker); // Records the sizes of `TargetItem`s. static void RecordTargetItemSizes(const std::vector<TargetItem>& items); }; } // namespace ash #endif // CHROME_BROWSER_ASH_CROSAPI_BROWSER_DATA_MIGRATOR_H_
blueboxd/chromium-legacy
base/check_op.h
<reponame>blueboxd/chromium-legacy<gh_stars>10-100 // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_CHECK_OP_H_ #define BASE_CHECK_OP_H_ #include <cstddef> #include <string> #include <type_traits> #include "base/check.h" #include "base/template_util.h" // This header defines the (DP)CHECK_EQ etc. macros. // // (DP)CHECK_EQ(x, y) is similar to (DP)CHECK(x == y) but will also log the // values of x and y if the condition doesn't hold. This works for basic types // and types with an operator<< or .ToString() method. // // The operands are evaluated exactly once, and even in build modes where e.g. // DCHECK is disabled, the operands and their stringification methods are still // referenced to avoid warnings about unused variables or functions. // // To support the stringification of the check operands, this header is // *significantly* larger than base/check.h, so it should be avoided in common // headers. // // This header also provides the (DP)CHECK macros (by including check.h), so if // you use e.g. both CHECK_EQ and CHECK, including this header is enough. If you // only use CHECK however, please include the smaller check.h instead. namespace logging { // Functions for turning check operand values into strings. // Caller takes ownership of the returned string. BASE_EXPORT char* CheckOpValueStr(int v); BASE_EXPORT char* CheckOpValueStr(unsigned v); BASE_EXPORT char* CheckOpValueStr(long v); BASE_EXPORT char* CheckOpValueStr(unsigned long v); BASE_EXPORT char* CheckOpValueStr(long long v); BASE_EXPORT char* CheckOpValueStr(unsigned long long v); BASE_EXPORT char* CheckOpValueStr(const void* v); BASE_EXPORT char* CheckOpValueStr(std::nullptr_t v); BASE_EXPORT char* CheckOpValueStr(double v); BASE_EXPORT char* CheckOpValueStr(const std::string& v); // Convert a streamable value to string out-of-line to avoid <sstream>. BASE_EXPORT char* StreamValToStr(const void* v, void (*stream_func)(std::ostream&, const void*)); #ifdef __has_builtin #define SUPPORTS_BUILTIN_ADDRESSOF (__has_builtin(__builtin_addressof)) #else #define SUPPORTS_BUILTIN_ADDRESSOF 0 #endif template <typename T> inline typename std::enable_if< base::internal::SupportsOstreamOperator<const T&>::value && !std::is_function<typename std::remove_pointer<T>::type>::value, char*>::type CheckOpValueStr(const T& v) { auto f = [](std::ostream& s, const void* p) { s << *reinterpret_cast<const T*>(p); }; // operator& might be overloaded, so do the std::addressof dance. // __builtin_addressof is preferred since it also handles Obj-C ARC pointers. // Some casting is still needed, because T might be volatile. #if SUPPORTS_BUILTIN_ADDRESSOF const void* vp = const_cast<const void*>( reinterpret_cast<const volatile void*>(__builtin_addressof(v))); #else const void* vp = reinterpret_cast<const void*>( const_cast<const char*>(&reinterpret_cast<const volatile char&>(v))); #endif return StreamValToStr(vp, f); } #undef SUPPORTS_BUILTIN_ADDRESSOF // Overload for types that have no operator<< but do have .ToString() defined. template <typename T> inline typename std::enable_if< !base::internal::SupportsOstreamOperator<const T&>::value && base::internal::SupportsToString<const T&>::value, char*>::type CheckOpValueStr(const T& v) { // .ToString() may not return a std::string, e.g. blink::WTF::String. return CheckOpValueStr(v.ToString()); } // Provide an overload for functions and function pointers. Function pointers // don't implicitly convert to void* but do implicitly convert to bool, so // without this function pointers are always printed as 1 or 0. (MSVC isn't // standards-conforming here and converts function pointers to regular // pointers, so this is a no-op for MSVC.) template <typename T> inline typename std::enable_if< std::is_function<typename std::remove_pointer<T>::type>::value, char*>::type CheckOpValueStr(const T& v) { return CheckOpValueStr(reinterpret_cast<const void*>(v)); } // We need overloads for enums that don't support operator<<. // (i.e. scoped enums where no operator<< overload was declared). template <typename T> inline typename std::enable_if< !base::internal::SupportsOstreamOperator<const T&>::value && std::is_enum<T>::value, char*>::type CheckOpValueStr(const T& v) { return CheckOpValueStr( static_cast<typename std::underlying_type<T>::type>(v)); } // Captures the result of a CHECK_op and facilitates testing as a boolean. class CheckOpResult { public: // An empty result signals success. constexpr CheckOpResult() {} // A non-success result. expr_str is something like "foo != bar". v1_str and // v2_str are the stringified run-time values of foo and bar. Takes ownership // of v1_str and v2_str. BASE_EXPORT CheckOpResult(const char* expr_str, char* v1_str, char* v2_str); // Returns true if the check succeeded. constexpr explicit operator bool() const { return !message_; } friend class CheckError; private: char* message_ = nullptr; }; #if defined(OFFICIAL_BUILD) && defined(NDEBUG) // Discard log strings to reduce code bloat. #define CHECK_OP(name, op, val1, val2) CHECK((val1)op(val2)) #else // Helper macro for binary operators. // The 'switch' is used to prevent the 'else' from being ambiguous when the // macro is used in an 'if' clause such as: // if (a == 1) // CHECK_EQ(2, a); #define CHECK_OP(name, op, val1, val2) \ switch (0) \ case 0: \ default: \ if (::logging::CheckOpResult true_if_passed = \ ::logging::Check##name##Impl((val1), (val2), \ #val1 " " #op " " #val2)) \ ; \ else \ ::logging::CheckError::CheckOp(__FILE__, __LINE__, &true_if_passed) \ .stream() #endif // The second overload avoids address-taking of static members for // fundamental types. #define DEFINE_CHECK_OP_IMPL(name, op) \ template <typename T, typename U, \ std::enable_if_t<!std::is_fundamental<T>::value || \ !std::is_fundamental<U>::value, \ int> = 0> \ constexpr ::logging::CheckOpResult Check##name##Impl( \ const T& v1, const U& v2, const char* expr_str) { \ if (ANALYZER_ASSUME_TRUE(v1 op v2)) \ return ::logging::CheckOpResult(); \ return ::logging::CheckOpResult(expr_str, CheckOpValueStr(v1), \ CheckOpValueStr(v2)); \ } \ template <typename T, typename U, \ std::enable_if_t<std::is_fundamental<T>::value && \ std::is_fundamental<U>::value, \ int> = 0> \ constexpr ::logging::CheckOpResult Check##name##Impl(T v1, U v2, \ const char* expr_str) { \ if (ANALYZER_ASSUME_TRUE(v1 op v2)) \ return ::logging::CheckOpResult(); \ return ::logging::CheckOpResult(expr_str, CheckOpValueStr(v1), \ CheckOpValueStr(v2)); \ } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wparentheses-equality" // clang-format off DEFINE_CHECK_OP_IMPL(EQ, ==) DEFINE_CHECK_OP_IMPL(NE, !=) DEFINE_CHECK_OP_IMPL(LE, <=) DEFINE_CHECK_OP_IMPL(LT, < ) DEFINE_CHECK_OP_IMPL(GE, >=) DEFINE_CHECK_OP_IMPL(GT, > ) #undef DEFINE_CHECK_OP_IMPL #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2) #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2) #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2) #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2) #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2) #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2) // clang-format on #pragma clang diagnostic pop #if DCHECK_IS_ON() #define DCHECK_OP(name, op, val1, val2) \ switch (0) \ case 0: \ default: \ if (::logging::CheckOpResult true_if_passed = \ ::logging::Check##name##Impl((val1), (val2), \ #val1 " " #op " " #val2)) \ ; \ else \ ::logging::CheckError::DCheckOp(__FILE__, __LINE__, &true_if_passed) \ .stream() #else // Don't do any evaluation but still reference the same stuff as when enabled. #define DCHECK_OP(name, op, val1, val2) \ EAT_CHECK_STREAM_PARAMS((::logging::CheckOpValueStr(val1), \ ::logging::CheckOpValueStr(val2), (val1)op(val2))) #endif // clang-format off #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2) #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2) #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2) #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2) #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2) #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2) // clang-format on } // namespace logging #endif // BASE_CHECK_OP_H_
blueboxd/chromium-legacy
components/viz/common/shared_element_resource_id.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VIZ_COMMON_SHARED_ELEMENT_RESOURCE_ID_H_ #define COMPONENTS_VIZ_COMMON_SHARED_ELEMENT_RESOURCE_ID_H_ #include <vector> #include "components/viz/common/viz_common_export.h" namespace viz { // See share_element_resource_id.mojom for details. class VIZ_COMMON_EXPORT SharedElementResourceId { public: // Generates a new id. static SharedElementResourceId Generate(); // For mojo deserialization. explicit SharedElementResourceId(uint32_t id); // Creates an invalid id. SharedElementResourceId(); ~SharedElementResourceId(); bool operator==(const SharedElementResourceId& o) const { return id_ == o.id_; } bool operator!=(const SharedElementResourceId& o) const { return !(*this == o); } bool operator<(const SharedElementResourceId& o) const { return id_ < o.id_; } bool IsValid() const; std::string ToString() const; uint32_t id() const { return id_; } private: uint32_t id_; }; } // namespace viz #endif // COMPONENTS_VIZ_COMMON_SHARED_ELEMENT_RESOURCE_ID_H_
blueboxd/chromium-legacy
ui/compositor/compositor_animation_observer.h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_COMPOSITOR_COMPOSITOR_ANIMATION_OBSERVER_H_ #define UI_COMPOSITOR_COMPOSITOR_ANIMATION_OBSERVER_H_ #include "base/location.h" #include "base/time/time.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/compositor/compositor_export.h" namespace ui { class Compositor; class COMPOSITOR_EXPORT CompositorAnimationObserver { public: explicit CompositorAnimationObserver( const base::Location& location = FROM_HERE); virtual ~CompositorAnimationObserver(); virtual void OnAnimationStep(base::TimeTicks timestamp) = 0; virtual void OnCompositingShuttingDown(Compositor* compositor) = 0; void Start(); void Check(); private: base::Location location_; absl::optional<base::TimeTicks> start_; }; } // namespace ui #endif // UI_COMPOSITOR_COMPOSITOR_ANIMATION_OBSERVER_H_
blueboxd/chromium-legacy
chrome/browser/ui/android/autofill/authenticator_selection_dialog_view_android.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTHENTICATOR_SELECTION_DIALOG_VIEW_ANDROID_H_ #define CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTHENTICATOR_SELECTION_DIALOG_VIEW_ANDROID_H_ #include <jni.h> #include <stddef.h> #include <vector> #include "base/android/scoped_java_ref.h" #include "chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_view.h" #include "ui/android/window_android.h" namespace autofill { class CardUnmaskAuthenticationSelectionDialogController; struct CardUnmaskChallengeOption; // Android implementation of the CardUnmaskAuthenticationSelectionDialogView. // `CardUnmaskAuthenticationSelectionDialogControllerImpl` holds a pointer to // this View. The View is expected to call "delete this" on itself upon // dismissal. class AuthenticatorSelectionDialogViewAndroid : public CardUnmaskAuthenticationSelectionDialogView { public: explicit AuthenticatorSelectionDialogViewAndroid( CardUnmaskAuthenticationSelectionDialogController* controller); virtual ~AuthenticatorSelectionDialogViewAndroid(); AuthenticatorSelectionDialogViewAndroid( const AuthenticatorSelectionDialogViewAndroid&) = delete; AuthenticatorSelectionDialogViewAndroid& operator=( const AuthenticatorSelectionDialogViewAndroid&) = delete; // CardUnmaskAuthenticationSelectionDialogView. void Dismiss(bool user_closed_dialog) override; // Called by the Java code when an Authenticator selection is made. void OnOptionSelected(JNIEnv* env, const base::android::JavaParamRef<jstring>& authenticatorOptionIdentifier); // Called by the Java code when the authenticatior selection dialog is // dismissed. void OnDismissed(JNIEnv* env); // Show the dialog view. bool ShowDialog(ui::WindowAndroid* window_android); private: CardUnmaskAuthenticationSelectionDialogController* controller_; // The corresponding java object. base::android::ScopedJavaGlobalRef<jobject> java_object_; // Uses JNI to create and return Java AuthenticatorOptions given a vector of // CardUnmaskChallengeOptions. base::android::ScopedJavaLocalRef<jobject> CreateJavaAuthenticatorOptions( JNIEnv* env, const std::vector<CardUnmaskChallengeOption>& options); // Uses JNI to create and add AuthenticatorOptions to a Java List. void CreateJavaAuthenticatorOptionAndAddToList( JNIEnv* env, base::android::ScopedJavaLocalRef<jobject> jlist, const CardUnmaskChallengeOption& option); }; } // namespace autofill #endif // CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTHENTICATOR_SELECTION_DIALOG_VIEW_ANDROID_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/frame/fragment_directive.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FRAGMENT_DIRECTIVE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FRAGMENT_DIRECTIVE_H_ #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/core/frame/directive.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace blink { class Document; class ScriptState; class V8UnionRangeOrSelection; // This class implements the `window.fragmentDirective` web API and serves as a // home for features based on the fragment directive portion of a URL (the part // of the URL fragment that comes after ':~:'. See: // https://github.com/WICG/scroll-to-text-fragment/ class FragmentDirective : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: explicit FragmentDirective(Document& owner_document); ~FragmentDirective() override; // Gets all parsed directives of the template type. template <typename DirectiveType> HeapVector<Member<DirectiveType>> GetDirectives() { HeapVector<Member<DirectiveType>> to_return; for (const Member<Directive>& directive : directives_) { if (directive->GetType() == DirectiveType::ClassType()) { auto* typed_directive = static_cast<DirectiveType*>(directive.Get()); to_return.push_back(Member<DirectiveType>(typed_directive)); } } return to_return; } // If fragment directive is present in the given URL, we'll parse it into // Directive objects and strip it from the returned URL. This is used when a // URL is set on Document to implement the hiding of the fragment directive // from the page. KURL ConsumeFragmentDirective(const KURL& url); bool LastNavigationHadFragmentDirective() const { return last_navigation_had_fragment_directive_; } // Returns the length of the unparsed fragment directive string. // TODO(bokan): This is used only for metrics. It's not clear how useful they // still are. We should either remove the metrics and this method or move // this method to where the FragmentDirective is read and stripped. wtf_size_t LengthForMetrics() const { return fragment_directive_string_length_; } void Trace(Visitor*) const override; // Web-exposed FragmentDirective interface. const HeapVector<Member<Directive>>& items() const; ScriptPromise createSelectorDirective(ScriptState*, const V8UnionRangeOrSelection*); private: void ParseDirectives(const String& fragment_directive); HeapVector<Member<Directive>> directives_; Member<Document> owner_document_; wtf_size_t fragment_directive_string_length_ = 0; bool last_navigation_had_fragment_directive_ = false; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FRAGMENT_DIRECTIVE_H_
blueboxd/chromium-legacy
chrome/browser/ui/app_list/chrome_app_list_model_updater.h
<filename>chrome/browser/ui/app_list/chrome_app_list_model_updater.h // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_APP_LIST_CHROME_APP_LIST_MODEL_UPDATER_H_ #define CHROME_BROWSER_UI_APP_LIST_CHROME_APP_LIST_MODEL_UPDATER_H_ #include <map> #include <memory> #include <string> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "chrome/browser/ui/app_list/app_list_model_updater.h" namespace ash { class AppListController; } // namespace ash namespace app_list { class AppListReorderDelegate; } // namespace app_list class ChromeAppListItem; class ChromeAppListItemManager; class ChromeAppListModelUpdater : public AppListModelUpdater { public: ChromeAppListModelUpdater(Profile* profile, app_list::AppListReorderDelegate* order_delegate); ChromeAppListModelUpdater(const ChromeAppListModelUpdater&) = delete; ChromeAppListModelUpdater& operator=(const ChromeAppListModelUpdater&) = delete; ~ChromeAppListModelUpdater() override; void SetActive(bool active) override; // AppListModelUpdater: void AddItem(std::unique_ptr<ChromeAppListItem> app_item) override; void AddItemToFolder(std::unique_ptr<ChromeAppListItem> app_item, const std::string& folder_id) override; void RemoveItem(const std::string& id) override; void RemoveUninstalledItem(const std::string& id) override; void SetStatus(ash::AppListModelStatus status) override; void SetSearchEngineIsGoogle(bool is_google) override; void UpdateSearchBox(const std::u16string& text, bool initiated_by_user) override; void PublishSearchResults( const std::vector<ChromeSearchResult*>& results, const std::vector<ash::AppListSearchResultCategory>& categories) override; std::vector<ChromeSearchResult*> GetPublishedSearchResultsForTest() override; // Methods only used by ChromeAppListItem that talk to ash directly. void SetItemIconVersion(const std::string& id, int icon_version) override; void SetItemIcon(const std::string& id, const gfx::ImageSkia& icon) override; void SetItemName(const std::string& id, const std::string& name) override; void SetItemNameAndShortName(const std::string& id, const std::string& name, const std::string& short_name) override; void SetAppStatus(const std::string& id, ash::AppStatus app_status) override; void SetItemPosition(const std::string& id, const syncer::StringOrdinal& new_position) override; void SetItemIsPersistent(const std::string& id, bool is_persistent) override; void SetItemFolderId(const std::string& id, const std::string& folder_id) override; void SetNotificationBadgeColor(const std::string& id, const SkColor color) override; // Methods only used by ChromeSearchResult that talk to ash directly. void SetSearchResultMetadata( const std::string& id, std::unique_ptr<ash::SearchResultMetadata> metadata) override; void ActivateChromeItem(const std::string& id, int event_flags) override; void LoadAppIcon(const std::string& id) override; // Methods for item querying. ChromeAppListItem* FindItem(const std::string& id) override; std::vector<const ChromeAppListItem*> GetItems() const override; size_t ItemCount() override; std::vector<ChromeAppListItem*> GetTopLevelItems() const override; ChromeAppListItem* ItemAtForTest(size_t index) override; ChromeAppListItem* FindFolderItem(const std::string& folder_id) override; bool FindItemIndexForTest(const std::string& id, size_t* index) override; bool SearchEngineIsGoogle() override; void GetIdToAppListIndexMap(GetIdToAppListIndexMapCallback callback) override; size_t BadgedItemCount() override; void GetContextMenuModel(const std::string& id, GetMenuModelCallback callback) override; syncer::StringOrdinal CalculatePositionForNewItem( const ChromeAppListItem& new_item) override; syncer::StringOrdinal GetPositionBeforeFirstItem() const override; // Methods for AppListSyncableService: void UpdateAppItemFromSyncItem( app_list::AppListSyncableService::SyncItem* sync_item, bool update_name, bool update_folder) override; void NotifyProcessSyncChangesFinished() override; // Methods to handle model update from ash: void OnItemAdded(std::unique_ptr<ash::AppListItemMetadata> item) override; void OnItemUpdated(std::unique_ptr<ash::AppListItemMetadata> item) override; void OnFolderDeleted(std::unique_ptr<ash::AppListItemMetadata> item) override; void OnPageBreakItemDeleted(const std::string& id) override; void OnSortRequested(ash::AppListSortOrder order) override; // Methods to handle app list item updates initiated from ash: void HandleSetPosition(std::string id, const syncer::StringOrdinal& new_position) override; void AddObserver(AppListModelUpdaterObserver* observer) override; void RemoveObserver(AppListModelUpdaterObserver* observer) override; private: // Indicates the profile that the model updater is associated with. Profile* const profile_ = nullptr; // Provides the access to the methods for ordering app list items. app_list::AppListReorderDelegate* const order_delegate_; // A helper class to manage app list items. It never talks to ash. std::unique_ptr<ChromeAppListItemManager> item_manager_; // The most recently list of search results. std::vector<ChromeSearchResult*> published_results_; base::ObserverList<AppListModelUpdaterObserver> observers_; ash::AppListController* app_list_controller_ = nullptr; bool search_engine_is_google_ = false; base::WeakPtrFactory<ChromeAppListModelUpdater> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_UI_APP_LIST_CHROME_APP_LIST_MODEL_UPDATER_H_
blueboxd/chromium-legacy
chrome/browser/ui/webui/history_clusters/history_clusters_handler.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_HISTORY_CLUSTERS_HISTORY_CLUSTERS_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_HISTORY_CLUSTERS_HISTORY_CLUSTERS_HANDLER_H_ #include <string> #include "base/callback.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "base/task/cancelable_task_tracker.h" #include "chrome/browser/ui/webui/history_clusters/history_clusters.mojom.h" #include "components/history/core/browser/history_types.h" #include "components/history_clusters/core/history_clusters_service.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" class Profile; namespace content { class WebContents; } // namespace content namespace history_clusters { // Not in an anonymous namespace so that it can be tested. // TODO(manukh) Try to setup a complete `HistoryClusterHandler` for testing so // that we can test the public method `QueryClusters` directly instead. mojom::QueryResultPtr QueryClustersResultToMojom(Profile* profile, const std::string& query, bool is_continuation, QueryClustersResult result); // Handles bidirectional communication between the history clusters page and the // browser. class HistoryClustersHandler : public mojom::PageHandler, public HistoryClustersService::Observer { public: HistoryClustersHandler( mojo::PendingReceiver<mojom::PageHandler> pending_page_handler, Profile* profile, content::WebContents* web_contents); HistoryClustersHandler(const HistoryClustersHandler&) = delete; HistoryClustersHandler& operator=(const HistoryClustersHandler&) = delete; ~HistoryClustersHandler() override; // mojom::PageHandler: void SetPage(mojo::PendingRemote<mojom::Page> pending_page) override; void ToggleVisibility(bool visible, ToggleVisibilityCallback callback) override; void QueryClusters(mojom::QueryParamsPtr query_params) override; void RemoveVisits(std::vector<mojom::URLVisitPtr> visits, RemoveVisitsCallback callback) override; // HistoryClustersService::Observer: void OnDebugMessage(const std::string& message) override; private: // Called with the result of querying clusters. Subsequently, `query_result` // is sent to the JS to update the UI. `query_start_time` is also passed to // allow for performance logging. void OnClustersQueryResult(base::TimeTicks query_start_time, mojom::QueryResultPtr query_result); // Called with the set of removed visits. Subsequently, `visits` is sent to // the JS to update the UI. void OnVisitsRemoved(std::vector<mojom::URLVisitPtr> visits); Profile* profile_; content::WebContents* web_contents_; // Tracker for query requests to the HistoryClustersService. base::CancelableTaskTracker query_task_tracker_; // Tracker for remove requests to the HistoryClustersService. base::CancelableTaskTracker remove_task_tracker_; // Used to observe the service. base::ScopedObservation<HistoryClustersService, HistoryClustersService::Observer> service_observation_{this}; mojo::Remote<mojom::Page> page_; mojo::Receiver<mojom::PageHandler> page_handler_; base::WeakPtrFactory<HistoryClustersHandler> weak_ptr_factory_{this}; }; } // namespace history_clusters #endif // CHROME_BROWSER_UI_WEBUI_HISTORY_CLUSTERS_HISTORY_CLUSTERS_HANDLER_H_
blueboxd/chromium-legacy
device/bluetooth/floss/bluetooth_device_floss.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DEVICE_BLUETOOTH_FLOSS_BLUETOOTH_DEVICE_FLOSS_H_ #define DEVICE_BLUETOOTH_FLOSS_BLUETOOTH_DEVICE_FLOSS_H_ #include <string> #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "device/bluetooth/bluetooth_common.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/bluetooth_export.h" #include "device/bluetooth/floss/floss_adapter_client.h" namespace floss { class BluetoothAdapterFloss; struct Error; struct FlossDeviceId; // BluetoothDeviceFloss implements device::BluetoothDevice for platforms using // Floss (Linux front-end for Fluoride). Objects of this type should be managed // by BluetoothAdapterFloss, which also manages device lifetimes. // // This class is not thread-safe but is only called from the UI thread. class DEVICE_BLUETOOTH_EXPORT BluetoothDeviceFloss : public device::BluetoothDevice { public: BluetoothDeviceFloss(const BluetoothDeviceFloss&) = delete; BluetoothDeviceFloss& operator=(const BluetoothDeviceFloss&) = delete; BluetoothDeviceFloss(BluetoothAdapterFloss* adapter, const FlossDeviceId& device); ~BluetoothDeviceFloss() override; // BluetoothDevice override uint32_t GetBluetoothClass() const override; device::BluetoothTransport GetType() const override; std::string GetAddress() const override; AddressType GetAddressType() const override; VendorIDSource GetVendorIDSource() const override; uint16_t GetVendorID() const override; uint16_t GetProductID() const override; uint16_t GetDeviceID() const override; uint16_t GetAppearance() const override; absl::optional<std::string> GetName() const override; bool IsPaired() const override; bool IsConnected() const override; bool IsGattConnected() const override; bool IsConnectable() const override; bool IsConnecting() const override; #if defined(OS_CHROMEOS) bool IsBlockedByPolicy() const override; #endif UUIDSet GetUUIDs() const override; absl::optional<int8_t> GetInquiryRSSI() const override; absl::optional<int8_t> GetInquiryTxPower() const override; bool ExpectingPinCode() const override; bool ExpectingPasskey() const override; bool ExpectingConfirmation() const override; void GetConnectionInfo(ConnectionInfoCallback callback) override; void SetConnectionLatency(ConnectionLatency connection_latency, base::OnceClosure callback, ErrorCallback error_callback) override; void Connect(device::BluetoothDevice::PairingDelegate* pairing_delegate, ConnectCallback callback) override; void SetPinCode(const std::string& pincode) override; void SetPasskey(uint32_t passkey) override; void ConfirmPairing() override; void RejectPairing() override; void CancelPairing() override; void Disconnect(base::OnceClosure callback, ErrorCallback error_callback) override; void Forget(base::OnceClosure callback, ErrorCallback error_callback) override; void ConnectToService(const device::BluetoothUUID& uuid, ConnectToServiceCallback callback, ConnectToServiceErrorCallback error_callback) override; void ConnectToServiceInsecurely( const device::BluetoothUUID& uuid, ConnectToServiceCallback callback, ConnectToServiceErrorCallback error_callback) override; std::unique_ptr<device::BluetoothGattConnection> CreateBluetoothGattConnectionObject() override; void SetGattServicesDiscoveryComplete(bool complete) override; bool IsGattServicesDiscoveryComplete() const override; void Pair(device::BluetoothDevice::PairingDelegate* pairing_delegate, ConnectCallback callback) override; #if BUILDFLAG(IS_CHROMEOS_ASH) void ExecuteWrite(base::OnceClosure callback, ExecuteWriteErrorCallback error_callback) override; void AbortWrite(base::OnceClosure callback, AbortWriteErrorCallback error_callback) override; #endif void SetName(const std::string& name); void SetBondState(FlossAdapterClient::BondState bond_state); protected: // BluetoothDevice override void CreateGattConnectionImpl( absl::optional<device::BluetoothUUID> service_uuid) override; void DisconnectGatt() override; private: // Method for connecting to this device. void ConnectInternal(ConnectCallback callback); void OnConnect(ConnectCallback callback); void OnConnectError(ConnectCallback callback, const Error& error); // Used if a Connect() is called but requires Pairing. void OnPairDuringConnect(ConnectCallback callback); void OnPairDuringConnectError(ConnectCallback callback, const Error& error); void OnDisconnect(base::OnceClosure callback); void OnDisconnectError(ErrorCallback error_callback, const Error& error); void OnPair(ConnectCallback callback); void OnPairError(ConnectCallback callback, const Error& error); void OnCancelPairingError(const Error& error); void OnForgetError(ErrorCallback error_callback, const Error& error); // Address of this device. Changing this should necessitate creating a new // BluetoothDeviceFloss object. const std::string address_; // Name of this device. Can be queried later and isn't mandatory for creation. std::string name_; // Whether the device is bonded/paired. FlossAdapterClient::BondState bond_state_ = FlossAdapterClient::BondState::kNotBonded; base::WeakPtrFactory<BluetoothDeviceFloss> weak_ptr_factory_{this}; }; } // namespace floss #endif // DEVICE_BLUETOOTH_FLOSS_BLUETOOTH_DEVICE_FLOSS_H_
tum-i22/munch
coreutils/patch.c
#undef initialize_main void initialize_main(int *argc, char ***argv) { char str[SIZE]; char *iargv[SIZE]; int iargc; char temp[SIZE] = {'\0'}; char *env; char env_var[SIZE] = {'\0'}; int quotes = 0; int len = 0; int env_var_size = 0; int pos = 0; int i = 0; int env_flag = 0; if (fgets (str, SIZE, stdin) == NULL ) { perror("Error while reading from stdin."); exit(EXIT_FAILURE); } iargv[0] = (*argv)[0]; iargc = 1; len = strlen(str); for(i = 0; i < len; i++) { if(str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r') { if(env_flag) { env_flag = 0; env_var[env_var_size] = '\0'; if(strlen(env_var) == 1) temp[pos++] = '$'; else { env = getenv(&env_var[1]); if(env != NULL) { strncpy(&temp[pos], env, strlen(env)); pos += strlen(env); } } env_var[0] = '\0'; env_var_size = 0; } if(quotes == 0) { if(strlen(temp) > 0) { temp[pos] = '\0'; iargv[iargc] = (char *) malloc(pos); if(iargv[iargc] == NULL) { perror("Error while allocating memory."); exit(EXIT_FAILURE); } strncpy(iargv[iargc++], temp, pos); temp[0] = '\0'; pos = 0; } } else temp[pos++] = str[i]; } else if(str[i] == '"' || str[i] == '\'') { if(quotes == 0) quotes++; else { quotes--; if(env_flag) { env_flag = 0; env_var[env_var_size] = '\0'; if(strlen(env_var) == 1) { temp[pos++] = '$'; } else { env = getenv(&env_var[1]); if(env != NULL) { strncpy(&temp[pos], env, strlen(env)); pos += strlen(env); } } env_var[0] = '\0'; env_var_size = 0; } if(strlen(temp) > 0) { temp[pos] = '\0'; iargv[iargc] = (char *) malloc(pos); strncpy(iargv[iargc++], temp, pos); temp[0] = '\0'; pos = 0; } } } else if(str[i] == '$') { env_flag = 1; env_var[env_var_size++] = str[i]; } else { if(env_flag) env_var[env_var_size++] = str[i]; else temp[pos++] = str[i]; } } *argc = iargc; *argv = iargv; }
CM-Archive/android_external_strace
strace/linux/sparc64/dummy2.h
/* * Copyright (c) 1993, 1994, 1995 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: dummy2.h,v 1.1 2004/07/12 07:44:08 roland Exp $ */ /* still unfinished */ #define solaris_sysmp printargs #define solaris_sginap printargs #define solaris_sgikopt printargs #define solaris_sysmips printargs #define solaris_sigreturn printargs #define solaris_recvmsg printargs #define solaris_sendmsg printargs #define solaris_nfssvc printargs #define solaris_getfh printargs #define solaris_async_daemon printargs #define solaris_exportfs printargs #define solaris_BSD_getime printargs #define solaris_sproc printargs #define solaris_procblk printargs #define solaris_sprocsp printargs #define solaris_msync printargs #define solaris_madvise printargs #define solaris_pagelock printargs #define solaris_quotactl printargs #define solaris_cacheflush printargs #define solaris_cachectl printargs #define solaris_nuname printargs #define solaris_sigpoll printargs #define solaris_swapctl printargs #define solaris_sigstack printargs #define solaris_sigsendset printargs #define solaris_priocntl printargs #define solaris_ksigqueue printargs #define solaris_lwp_sema_wait printargs #define solaris_memcntl printargs #define solaris_syscall printargs #define solaris_clocal printargs #define solaris_syssun printargs #define solaris_sysi86 printargs #define solaris_sysmachine printargs #define solaris_plock printargs #define solaris_pathconf printargs #define solaris_sigtimedwait printargs #define solaris_ulimit printargs #define solaris_ptrace printargs #define solaris_stty printargs #define solaris_lwp_info printargs #define solaris_priocntlsys printargs #define solaris_hrtsys printargs #define solaris_xenix printargs #define solaris_statfs printargs #define solaris_fstatfs printargs #define solaris_statvfs printargs #define solaris_fstatvfs printargs #define solaris_fork1 printargs #define solaris_sigsendsys printargs #define solaris_gtty printargs #define solaris_vtrace printargs #define solaris_fpathconf printargs #define solaris_evsys printargs #define solaris_acct printargs #define solaris_exec printargs #define solaris_lwp_sema_post printargs #define solaris_nfssys printargs #define solaris_sigaltstack printargs #define solaris_uadmin printargs #define solaris_umount printargs #define solaris_modctl printargs #define solaris_acancel printargs #define solaris_async printargs #define solaris_evtrapret printargs #define solaris_lwp_create printargs #define solaris_lwp_exit printargs #define solaris_lwp_suspend printargs #define solaris_lwp_continue printargs #define solaris_lwp_kill printargs #define solaris_lwp_self printargs #define solaris_lwp_setprivate printargs #define solaris_lwp_getprivate printargs #define solaris_lwp_wait printargs #define solaris_lwp_mutex_unlock printargs #define solaris_lwp_mutex_lock printargs #define solaris_lwp_cond_wait printargs #define solaris_lwp_cond_signal printargs #define solaris_lwp_cond_broadcast printargs #define solaris_llseek printargs #define solaris_inst_sync printargs #define solaris_auditsys printargs #define solaris_processor_bind printargs #define solaris_processor_info printargs #define solaris_p_online printargs #define solaris_sigqueue printargs #define solaris_clock_gettime printargs #define solaris_clock_settime printargs #define solaris_clock_getres printargs #define solaris_nanosleep printargs #define solaris_timer_create printargs #define solaris_timer_delete printargs #define solaris_timer_settime printargs #define solaris_timer_gettime printargs #define solaris_timer_getoverrun printargs #define solaris_signal printargs #define solaris_sigset printargs #define solaris_sighold printargs #define solaris_sigrelse printargs #define solaris_sigignore printargs #define solaris_sigpause printargs #define solaris_msgctl printargs #define solaris_msgget printargs #define solaris_msgrcv printargs #define solaris_msgsnd printargs #define solaris_shmat printargs #define solaris_shmctl printargs #define solaris_shmdt printargs #define solaris_shmget printargs #define solaris_semctl printargs #define solaris_semget printargs #define solaris_semop printargs #define solaris_olduname printargs #define solaris_ustat printargs #define solaris_fusers printargs #define solaris_sysfs1 printargs #define solaris_sysfs2 printargs #define solaris_sysfs3 printargs /* like another call */ #define solaris_lchown solaris_chown #define solaris_setuid solaris_close #define solaris_seteuid solaris_close #define solaris_setgid solaris_close #define solaris_setegid solaris_close #define solaris_vhangup solaris_close #define solaris_fdsync solaris_close #define solaris_sigfillset solaris_sigpending #define solaris_vfork solaris_fork #define solaris_ksigaction solaris_sigaction #define solaris_BSDgetpgrp solaris_getpgrp #define solaris_BSDsetpgrp solaris_setpgrp #define solaris_waitsys solaris_waitid /* printargs does the right thing */ #define solaris_sync printargs #define solaris_profil printargs #define solaris_yield printargs #define solaris_pause printargs #define solaris_sethostid printargs /* subfunction entry points */ #define solaris_pgrpsys printargs #define solaris_sigcall printargs #define solaris_msgsys printargs #define solaris_shmsys printargs #define solaris_semsys printargs #define solaris_utssys printargs #define solaris_sysfs printargs #define solaris_spcall printargs #define solaris_context printargs /* same as linux */ #define solaris_exit sys_exit #define solaris_fork sys_fork #define solaris_read sys_read #define solaris_write sys_write #define solaris_close sys_close #define solaris_creat sys_creat #define solaris_link sys_link #define solaris_unlink sys_unlink #define solaris_chdir sys_chdir #define solaris_time sys_time #define solaris_chmod sys_chmod #define solaris_lseek sys_lseek #define solaris_stime sys_stime #define solaris_alarm sys_alarm #define solaris_utime sys_utime #define solaris_access sys_access #define solaris_nice sys_nice #define solaris_dup sys_dup #define solaris_pipe sys_pipe #define solaris_times sys_times #define solaris_execve sys_execve #define solaris_umask sys_umask #define solaris_chroot sys_chroot #define solaris_rmdir sys_rmdir #define solaris_mkdir sys_mkdir #define solaris_getdents sys_getdents #define solaris_poll sys_poll #define solaris_symlink sys_symlink #define solaris_readlink sys_readlink #define solaris_setgroups sys_setgroups #define solaris_getgroups sys_getgroups #define solaris_fchmod sys_fchmod #define solaris_fchown sys_fchown #define solaris_mprotect sys_mprotect #define solaris_munmap sys_munmap #define solaris_readv sys_readv #define solaris_writev sys_writev #define solaris_chown sys_chown #define solaris_rename sys_rename #define solaris_gettimeofday sys_gettimeofday #define solaris_getitimer sys_getitimer #define solaris_setitimer sys_setitimer #define solaris_brk sys_brk #define solaris_mmap sys_mmap #define solaris_getsid sys_getsid #define solaris_setsid sys_setsid #define solaris_getpgid sys_getpgid #define solaris_setpgid sys_setpgid #define solaris_getpgrp sys_getpgrp /* These are handled according to current_personality */ #define solaris_xstat sys_xstat #define solaris_fxstat sys_fxstat #define solaris_lxstat sys_lxstat #define solaris_xmknod sys_xmknod #define solaris_stat sys_stat #define solaris_fstat sys_fstat #define solaris_lstat sys_lstat #define solaris_pread sys_pread #define solaris_pwrite sys_pwrite #define solaris_ioctl sys_ioctl #define solaris_mknod sys_mknod /* To be done */ #define solaris_mount printargs #define solaris_sysinfo printargs #define solaris_sysconfig printargs #define solaris_getpmsg printargs #define solaris_putpmsg printargs #define solaris_wait printargs #define solaris_waitid printargs #define solaris_sigsuspend printargs #define solaris_setpgrp printargs #define solaris_getcontext printargs #define solaris_setcontext printargs #define solaris_getpid printargs #define solaris_getuid printargs #define solaris_kill printargs #define solaris_getgid printargs #define solaris_fcntl printargs #define solaris_getmsg printargs #define solaris_putmsg printargs #define solaris_sigprocmask printargs #define solaris_sigaction printargs #define solaris_sigpending printargs #define solaris_mincore printargs #define solaris_fchdir printargs #define solaris_setrlimit printargs #define solaris_getrlimit printargs #define solaris_uname printargs #define solaris_adjtime printargs #define solaris_fchroot printargs #define solaris_utimes printargs #if DONE #define solaris_open printargs #endif
CM-Archive/android_external_strace
strace/linux/sparc64/syscall1.h
/* * Copyright (c) 1993, 1994, 1995 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: syscall1.h,v 1.1 2004/07/12 07:44:08 roland Exp $ */ #define SOLARIS_syscall 0 #define SOLARIS_exit 1 #define SOLARIS_fork 2 #define SOLARIS_read 3 #define SOLARIS_write 4 #define SOLARIS_open 5 #define SOLARIS_close 6 #define SOLARIS_wait 7 #define SOLARIS_creat 8 #define SOLARIS_link 9 #define SOLARIS_unlink 10 #define SOLARIS_exec 11 #define SOLARIS_chdir 12 #define SOLARIS_time 13 #define SOLARIS_mknod 14 #define SOLARIS_chmod 15 #define SOLARIS_chown 16 #define SOLARIS_brk 17 #define SOLARIS_stat 18 #define SOLARIS_lseek 19 #define SOLARIS_getpid 20 #define SOLARIS_mount 21 #define SOLARIS_umount 22 #define SOLARIS_setuid 23 #define SOLARIS_getuid 24 #define SOLARIS_stime 25 #define SOLARIS_ptrace 26 #define SOLARIS_alarm 27 #define SOLARIS_fstat 28 #define SOLARIS_pause 29 #define SOLARIS_utime 30 #define SOLARIS_stty 31 #define SOLARIS_gtty 32 #define SOLARIS_access 33 #define SOLARIS_nice 34 #define SOLARIS_statfs 35 #define SOLARIS_sync 36 #define SOLARIS_kill 37 #define SOLARIS_fstatfs 38 #define SOLARIS_pgrpsys 39 #define SOLARIS_xenix 40 #define SOLARIS_dup 41 #define SOLARIS_pipe 42 #define SOLARIS_times 43 #define SOLARIS_profil 44 #define SOLARIS_plock 45 #define SOLARIS_setgid 46 #define SOLARIS_getgid 47 #define SOLARIS_signal 48 #define SOLARIS_msgsys 49 #define SOLARIS_syssun 50 #define SOLARIS_acct 51 #define SOLARIS_shmsys 52 #define SOLARIS_semsys 53 #define SOLARIS_ioctl 54 #define SOLARIS_uadmin 55 #define SOLARIS_utssys 57 #define SOLARIS_fdsync 58 #define SOLARIS_execve 59 #define SOLARIS_umask 60 #define SOLARIS_chroot 61 #define SOLARIS_fcntl 62 #define SOLARIS_ulimit 63 #define SOLARIS_rmdir 79 #define SOLARIS_mkdir 80 #define SOLARIS_getdents 81 #define SOLARIS_sysfs 84 #define SOLARIS_getmsg 85 #define SOLARIS_putmsg 86 #define SOLARIS_poll 87 #define SOLARIS_lstat 88 #define SOLARIS_symlink 89 #define SOLARIS_readlink 90 #define SOLARIS_setgroups 91 #define SOLARIS_getgroups 92 #define SOLARIS_fchmod 93 #define SOLARIS_fchown 94 #define SOLARIS_sigprocmask 95 #define SOLARIS_sigsuspend 96 #define SOLARIS_sigaltstack 97 #define SOLARIS_sigaction 98 #define SOLARIS_sigpending 99 #define SOLARIS_context 100 #define SOLARIS_evsys 101 #define SOLARIS_evtrapret 102 #define SOLARIS_statvfs 103 #define SOLARIS_fstatvfs 104 #define SOLARIS_nfssys 106 #define SOLARIS_waitsys 107 #define SOLARIS_sigsendsys 108 #define SOLARIS_hrtsys 109 #define SOLARIS_acancel 110 #define SOLARIS_async 111 #define SOLARIS_priocntlsys 112 #define SOLARIS_pathconf 113 #define SOLARIS_mincore 114 #define SOLARIS_mmap 115 #define SOLARIS_mprotect 116 #define SOLARIS_munmap 117 #define SOLARIS_fpathconf 118 #define SOLARIS_vfork 119 #define SOLARIS_fchdir 120 #define SOLARIS_readv 121 #define SOLARIS_writev 122 #define SOLARIS_xstat 123 #define SOLARIS_lxstat 124 #define SOLARIS_fxstat 125 #define SOLARIS_xmknod 126 #define SOLARIS_clocal 127 #define SOLARIS_setrlimit 128 #define SOLARIS_getrlimit 129 #define SOLARIS_lchown 130 #define SOLARIS_memcntl 131 #define SOLARIS_getpmsg 132 #define SOLARIS_putpmsg 133 #define SOLARIS_rename 134 #define SOLARIS_uname 135 #define SOLARIS_setegid 136 #define SOLARIS_sysconfig 137 #define SOLARIS_adjtime 138 #define SOLARIS_systeminfo 139 #define SOLARIS_seteuid 141 #define SOLARIS_vtrace 142 #define SOLARIS_fork1 143 #define SOLARIS_sigtimedwait 144 #define SOLARIS_lwp_info 145 #define SOLARIS_yield 146 #define SOLARIS_lwp_sema_wait 147 #define SOLARIS_lwp_sema_post 148 #define SOLARIS_modctl 152 #define SOLARIS_fchroot 153 #define SOLARIS_utimes 154 #define SOLARIS_vhangup 155 #define SOLARIS_gettimeofday 156 #define SOLARIS_getitimer 157 #define SOLARIS_setitimer 158 #define SOLARIS_lwp_create 159 #define SOLARIS_lwp_exit 160 #define SOLARIS_lwp_suspend 161 #define SOLARIS_lwp_continue 162 #define SOLARIS_lwp_kill 163 #define SOLARIS_lwp_self 164 #define SOLARIS_lwp_setprivate 165 #define SOLARIS_lwp_getprivate 166 #define SOLARIS_lwp_wait 167 #define SOLARIS_lwp_mutex_unlock 168 #define SOLARIS_lwp_mutex_lock 169 #define SOLARIS_lwp_cond_wait 170 #define SOLARIS_lwp_cond_signal 171 #define SOLARIS_lwp_cond_broadcast 172 #define SOLARIS_pread 173 #define SOLARIS_pwrite 174 #define SOLARIS_llseek 175 #define SOLARIS_inst_sync 176 #define SOLARIS_kaio 178 #define SOLARIS_tsolsys 184 #define SOLARIS_acl 185 #define SOLARIS_auditsys 186 #define SOLARIS_processor_bind 187 #define SOLARIS_processor_info 188 #define SOLARIS_p_online 189 #define SOLARIS_sigqueue 190 #define SOLARIS_clock_gettime 191 #define SOLARIS_clock_settime 192 #define SOLARIS_clock_getres 193 #define SOLARIS_timer_create 194 #define SOLARIS_timer_delete 195 #define SOLARIS_timer_settime 196 #define SOLARIS_timer_gettime 197 #define SOLARIS_timer_getoverrun 198 #define SOLARIS_nanosleep 199 #define SOLARIS_facl 200 #define SOLARIS_door 201 #define SOLARIS_setreuid 202 #define SOLARIS_setregid 203 #define SOLARIS_signotifywait 210 #define SOLARIS_lwp_sigredirect 211 #define SOLARIS_lwp_alarm 212 #include "dummy2.h" extern int solaris_syscall(); extern int solaris_exit(); extern int solaris_fork(); extern int solaris_read(); extern int solaris_write(); extern int solaris_open(); extern int solaris_close(); extern int solaris_wait(); extern int solaris_creat(); extern int solaris_link(); extern int solaris_unlink(); extern int solaris_exec(); extern int solaris_chdir(); extern int solaris_time(); extern int solaris_mknod(); extern int solaris_chmod(); extern int solaris_chown(); extern int solaris_brk(); extern int solaris_stat(); extern int solaris_lseek(); extern int solaris_getpid(); extern int solaris_mount(); extern int solaris_umount(); extern int solaris_setuid(); extern int solaris_getuid(); extern int solaris_stime(); extern int solaris_ptrace(); extern int solaris_alarm(); extern int solaris_fstat(); extern int solaris_pause(); extern int solaris_utime(); extern int solaris_stty(); extern int solaris_gtty(); extern int solaris_access(); extern int solaris_nice(); extern int solaris_statfs(); extern int solaris_sync(); extern int solaris_kill(); extern int solaris_fstatfs(); extern int solaris_pgrpsys(); extern int solaris_setpgrp(); extern int solaris_xenix(); extern int solaris_syssgi(); extern int solaris_dup(); extern int solaris_pipe(); extern int solaris_times(); extern int solaris_profil(); extern int solaris_plock(); extern int solaris_setgid(); extern int solaris_getgid(); extern int solaris_sigcall(); extern int solaris_msgsys(); extern int solaris_syssun(); extern int solaris_sysi86(); extern int solaris_sysmips(); extern int solaris_sysmachine(); extern int solaris_acct(); extern int solaris_shmsys(); extern int solaris_semsys(); extern int solaris_ioctl(); extern int solaris_uadmin(); extern int solaris_utssys(); extern int solaris_fdsync(); extern int solaris_execve(); extern int solaris_umask(); extern int solaris_chroot(); extern int solaris_fcntl(); extern int solaris_ulimit(); extern int solaris_rmdir(); extern int solaris_mkdir(); extern int solaris_getdents(); extern int solaris_sysfs(); extern int solaris_getmsg(); extern int solaris_putmsg(); extern int solaris_poll(); extern int solaris_lstat(); extern int solaris_symlink(); extern int solaris_readlink(); extern int solaris_setgroups(); extern int solaris_getgroups(); extern int solaris_fchmod(); extern int solaris_fchown(); extern int solaris_sigprocmask(); extern int solaris_sigsuspend(); extern int solaris_sigaltstack(); extern int solaris_sigaction(); extern int solaris_spcall(); extern int solaris_context(); extern int solaris_evsys(); extern int solaris_evtrapret(); extern int solaris_statvfs(); extern int solaris_fstatvfs(); extern int solaris_nfssys(); extern int solaris_waitid(); extern int solaris_sigsendsys(); extern int solaris_hrtsys(); extern int solaris_acancel(); extern int solaris_async(); extern int solaris_priocntlsys(); extern int solaris_pathconf(); extern int solaris_mincore(); extern int solaris_mmap(); extern int solaris_mprotect(); extern int solaris_munmap(); extern int solaris_fpathconf(); extern int solaris_vfork(); extern int solaris_fchdir(); extern int solaris_readv(); extern int solaris_writev(); extern int solaris_xstat(); extern int solaris_lxstat(); extern int solaris_fxstat(); extern int solaris_xmknod(); extern int solaris_clocal(); extern int solaris_setrlimit(); extern int solaris_getrlimit(); extern int solaris_lchown(); extern int solaris_memcntl(); extern int solaris_getpmsg(); extern int solaris_putpmsg(); extern int solaris_rename(); extern int solaris_uname(); extern int solaris_setegid(); extern int solaris_sysconfig(); extern int solaris_adjtime(); extern int solaris_sysinfo(); extern int solaris_seteuid(); extern int solaris_vtrace(); extern int solaris_fork1(); extern int solaris_sigtimedwait(); extern int solaris_lwp_info(); extern int solaris_yield(); extern int solaris_lwp_sema_wait(); extern int solaris_lwp_sema_post(); extern int solaris_modctl(); extern int solaris_fchroot(); extern int solaris_utimes(); extern int solaris_vhangup(); extern int solaris_gettimeofday(); extern int solaris_getitimer(); extern int solaris_setitimer(); extern int solaris_lwp_create(); extern int solaris_lwp_exit(); extern int solaris_lwp_suspend(); extern int solaris_lwp_continue(); extern int solaris_lwp_kill(); extern int solaris_lwp_self(); extern int solaris_lwp_setprivate(); extern int solaris_lwp_getprivate(); extern int solaris_lwp_wait(); extern int solaris_lwp_mutex_unlock(); extern int solaris_lwp_mutex_lock(); extern int solaris_lwp_cond_wait(); extern int solaris_lwp_cond_signal(); extern int solaris_lwp_cond_broadcast(); extern int solaris_pread(); extern int solaris_pwrite(); extern int solaris_llseek(); extern int solaris_inst_sync(); extern int solaris_auditsys(); extern int solaris_processor_bind(); extern int solaris_processor_info(); extern int solaris_p_online(); extern int solaris_sigqueue(); extern int solaris_clock_gettime(); extern int solaris_clock_settime(); extern int solaris_clock_getres(); extern int solaris_timer_create(); extern int solaris_timer_delete(); extern int solaris_timer_settime(); extern int solaris_timer_gettime(); extern int solaris_timer_getoverrun(); extern int solaris_nanosleep(); /* solaris_pgrpsys subcalls */ extern int solaris_getpgrp(), solaris_setpgrp(), solaris_getsid(); extern int solaris_setsid(), solaris_getpgid(), solaris_setpgid(); #define SOLARIS_pgrpsys_subcall 300 #define SOLARIS_getpgrp (SOLARIS_pgrpsys_subcall + 0) #define SOLARIS_setpgrp (SOLARIS_pgrpsys_subcall + 1) #define SOLARIS_getsid (SOLARIS_pgrpsys_subcall + 2) #define SOLARIS_setsid (SOLARIS_pgrpsys_subcall + 3) #define SOLARIS_getpgid (SOLARIS_pgrpsys_subcall + 4) #define SOLARIS_setpgid (SOLARIS_pgrpsys_subcall + 5) #define SOLARIS_pgrpsys_nsubcalls 6 /* solaris_sigcall subcalls */ #undef SOLARIS_signal #define SOLARIS_sigcall 48 extern int solaris_signal(), solaris_sigset(), solaris_sighold(); extern int solaris_sigrelse(), solaris_sigignore(), solaris_sigpause(); #define SOLARIS_sigcall_subcall 310 #define SOLARIS_signal (SOLARIS_sigcall_subcall + 0) #define SOLARIS_sigset (SOLARIS_sigcall_subcall + 1) #define SOLARIS_sighold (SOLARIS_sigcall_subcall + 2) #define SOLARIS_sigrelse (SOLARIS_sigcall_subcall + 3) #define SOLARIS_sigignore (SOLARIS_sigcall_subcall + 4) #define SOLARIS_sigpause (SOLARIS_sigcall_subcall + 5) #define SOLARIS_sigcall_nsubcalls 6 /* msgsys subcalls */ extern int solaris_msgget(), solaris_msgctl(), solaris_msgrcv(), solaris_msgsnd(); #define SOLARIS_msgsys_subcall 320 #define SOLARIS_msgget (SOLARIS_msgsys_subcall + 0) #define SOLARIS_msgctl (SOLARIS_msgsys_subcall + 1) #define SOLARIS_msgrcv (SOLARIS_msgsys_subcall + 2) #define SOLARIS_msgsnd (SOLARIS_msgsys_subcall + 3) #define SOLARIS_msgsys_nsubcalls 4 /* shmsys subcalls */ extern int solaris_shmat(), solaris_shmctl(), solaris_shmdt(), solaris_shmget(); #define SOLARIS_shmsys_subcall 330 #define SOLARIS_shmat (SOLARIS_shmsys_subcall + 0) #define SOLARIS_shmctl (SOLARIS_shmsys_subcall + 1) #define SOLARIS_shmdt (SOLARIS_shmsys_subcall + 2) #define SOLARIS_shmget (SOLARIS_shmsys_subcall + 3) #define SOLARIS_shmsys_nsubcalls 4 /* semsys subcalls */ extern int solaris_semctl(), solaris_semget(), solaris_semop(); #define SOLARIS_semsys_subcall 340 #define SOLARIS_semctl (SOLARIS_semsys_subcall + 0) #define SOLARIS_semget (SOLARIS_semsys_subcall + 1) #define SOLARIS_semop (SOLARIS_semsys_subcall + 2) #define SOLARIS_semsys_nsubcalls 3 /* utssys subcalls */ extern int solaris_olduname(), solaris_ustat(), solaris_fusers(); #define SOLARIS_utssys_subcall 350 #define SOLARIS_olduname (SOLARIS_utssys_subcall + 0) /* 1 is unused */ #define SOLARIS_ustat (SOLARIS_utssys_subcall + 2) #define SOLARIS_fusers (SOLARIS_utssys_subcall + 3) #define SOLARIS_utssys_nsubcalls 4 /* sysfs subcalls */ extern int solaris_sysfs1(), solaris_sysfs2(), solaris_sysfs3(); #define SOLARIS_sysfs_subcall 360 /* 0 is unused */ #define SOLARIS_sysfs1 (SOLARIS_sysfs_subcall + 1) #define SOLARIS_sysfs2 (SOLARIS_sysfs_subcall + 2) #define SOLARIS_sysfs3 (SOLARIS_sysfs_subcall + 3) #define SOLARIS_sysfs_nsubcalls 4 /* solaris_spcall subcalls */ #undef SOLARIS_sigpending #define SOLARIS_spcall 99 extern int solaris_sigpending(), solaris_sigfillset(); #define SOLARIS_spcall_subcall 370 /* 0 is unused */ #define SOLARIS_sigpending (SOLARIS_spcall_subcall + 1) #define SOLARIS_sigfillset (SOLARIS_spcall_subcall + 2) #define SOLARIS_spcall_nsubcalls 3 /* solaris_context subcalls */ extern int solaris_getcontext(), solaris_setcontext(); #define SOLARIS_context_subcall 380 #define SOLARIS_getcontext (SOLARIS_context_subcall + 0) #define SOLARIS_setcontext (SOLARIS_context_subcall + 1) #define SOLARIS_context_nsubcalls 2
CM-Archive/android_external_strace
strace/linux/sparc/syscall.h
<gh_stars>1-10 /* * Copyright (c) 1991, 1992 <NAME> <<EMAIL>> * Copyright (c) 1993, 1994, 1995, 1996 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: syscall.h,v 1.10 2005/02/02 20:32:13 roland Exp $ */ #include "dummy.h" int sys_nosys(); int sys_nullsys(); int sys_errsys(); /* 1.1 processes and protection */ int sys_gethostid(),sys_sethostname(),sys_gethostname(),sys_getpid(); int sys_setdomainname(),sys_getdomainname(); int sys_fork(),sys_clone(),sys_exit(),sys_execv(),sys_execve(),sys_wait4(),sys_waitpid(); int sys_setuid(),sys_setgid(),sys_getuid(),sys_setreuid(),sys_getgid(),sys_getgroups(),sys_setregid(),sys_setgroups(); int sys_getpgrp(),sys_setpgrp(); int sys_setsid(), sys_setpgid(); int sys_uname(), sys_sysinfo(); /* 1.2 memory management */ int sys_brk(),sys_sbrk(),sys_sstk(); int sys_getpagesize(),sys_mmap(),sys_mctl(),sys_munmap(),sys_mprotect(),sys_mincore(), sys_mremap(); int sys_omsync(),sys_omadvise(), sys_madvise(),sys_mlockall(); /* 1.3 signals */ int sys_sigvec(),sys_sigblock(),sys_sigsetmask(),sys_sigpause(),sys_sigstack(),sys_sigcleanup(), sys_sigreturn(); int sys_kill(), sys_killpg(), sys_sigpending(), sys_signal(), sys_sigaction(), sys_sigsuspend(), sys_sigprocmask(); /* 1.4 timing and statistics */ int sys_gettimeofday(),sys_settimeofday(); int sys_adjtime(), sys_adjtimex(); int sys_getitimer(),sys_setitimer(); /* 1.5 descriptors */ int sys_getdtablesize(),sys_dup(),sys_dup2(),sys_close(); int sys_oldselect(),sys_select(),sys_getdopt(),sys_setdopt(),sys_fcntl(),sys_flock(); int sys_epoll_create(), sys_epoll_ctl(), sys_epoll_wait(); /* 1.6 resource controls */ int sys_getpriority(),sys_setpriority(),sys_getrusage(),sys_getrlimit(),sys_setrlimit(); int sys_oldquota(), sys_quotactl(); int sys_rtschedule(), sys_personality(); /* 1.7 system operation support */ int sys_mount(),sys_unmount(),sys_swapon(),sys_pivotroot(); int sys_sync(),sys_reboot(); int sys_sysacct(); int sys_auditsys(); /* 2.1 generic operations */ int sys_read(),sys_write(),sys_readv(),sys_writev(),sys_ioctl(); /* 2.1.1 asynch operations */ int sys_aioread(), sys_aiowrite(), sys_aiowait(), sys_aiocancel(); /* 2.2 file system */ int sys_chdir(),sys_chroot(); int sys_fchdir(),sys_fchroot(); int sys_mkdir(),sys_rmdir(),sys_getdirentries(); int sys_getdents(), sys_getdents64(), sys_readdir(); int sys_creat(),sys_open(),sys_mknod(),sys_unlink(),sys_stat(),sys_fstat(),sys_lstat(); int sys_chown(),sys_fchown(),sys_chmod(),sys_fchmod(),sys_utimes(); int sys_link(),sys_symlink(),sys_readlink(),sys_rename(); int sys_lseek(), sys_llseek(); int sys_truncate(),sys_ftruncate(),sys_access(),sys_fsync(),sys_sysctl(); int sys_statfs(),sys_fstatfs(),sys_msync(); int sys_stat64(), sys_lstat64(), sys_fstat64(); int sys_truncate64(), sys_ftruncate64(); /* 2.3 communications */ int sys_socket(),sys_bind(),sys_listen(),sys_accept(),sys_connect(); int sys_socketpair(),sys_sendto(),sys_send(),sys_recvfrom(),sys_recv(); int sys_sendmsg(),sys_recvmsg(),sys_shutdown(),sys_setsockopt(),sys_getsockopt(); int sys_getsockname(),sys_getpeername(),sys_pipe(); int sys_setresuid(), sys_setresgid(), sys_getresuid(), sys_getresgid(), sys_pread(); int sys_pwrite(), sys_getcwd(); int sys_sigaltstack(), sys_rt_sigprocmask(), sys_rt_sigaction(); int sys_rt_sigpending(), sys_rt_sigsuspend(), sys_rt_sigqueueinfo(); int sys_rt_sigtimedwait(), sys_prctl(), sys_poll(); int sys_sendfile(), sys_query_module(), sys_capget(), sys_capset(); int sys_create_module(), sys_init_module(); int sys_umask(); /* XXX */ int sys_sched_setparam(), sys_sched_getparam(); int sys_sched_setscheduler(), sys_sched_getscheduler(), sys_sched_yield(); int sys_sched_get_priority_max(), sys_sched_get_priority_min(); /* 2.3.1 SystemV-compatible IPC */ int sys_semsys(), sys_semctl(), sys_semget(); #define SYS_semsys_subcall 200 #define SYS_semsys_nsubcalls 3 #define SYS_semctl (SYS_semsys_subcall + 0) #define SYS_semget (SYS_semsys_subcall + 1) #define SYS_semop (SYS_semsys_subcall + 2) int sys_msgsys(), sys_msgget(), sys_msgctl(), sys_msgrcv(), sys_msgsnd(); #define SYS_msgsys_subcall 203 #define SYS_msgsys_nsubcalls 4 #define SYS_msgget (SYS_msgsys_subcall + 0) #define SYS_msgctl (SYS_msgsys_subcall + 1) #define SYS_msgrcv (SYS_msgsys_subcall + 2) #define SYS_msgsnd (SYS_msgsys_subcall + 3) int sys_shmsys(), sys_shmat(), sys_shmctl(), sys_shmdt(), sys_shmget(); #define SYS_shmsys_subcall 207 #define SYS_shmsys_nsubcalls 4 #define SYS_shmat (SYS_shmsys_subcall + 0) #define SYS_shmctl (SYS_shmsys_subcall + 1) #define SYS_shmdt (SYS_shmsys_subcall + 2) #define SYS_shmget (SYS_shmsys_subcall + 3) /* 2.4 processes */ int sys_ptrace(); /* 2.5 terminals */ /* emulations for backwards compatibility */ int sys_otime(); /* now use gettimeofday */ int sys_ostime(); /* now use settimeofday */ int sys_oalarm(); /* now use setitimer */ int sys_outime(); /* now use utimes */ int sys_opause(); /* now use sigpause */ int sys_onice(); /* now use setpriority,getpriority */ int sys_oftime(); /* now use gettimeofday */ int sys_osetpgrp(); /* ??? */ int sys_otimes(); /* now use getrusage */ int sys_ossig(); /* now use sigvec, etc */ int sys_ovlimit(); /* now use setrlimit,getrlimit */ int sys_ovtimes(); /* now use getrusage */ int sys_osetuid(); /* now use setreuid */ int sys_osetgid(); /* now use setregid */ int sys_ostat(); /* now use stat */ int sys_ofstat(); /* now use fstat */ /* BEGIN JUNK */ int sys_profil(); /* 'cuz sys calls are interruptible */ int sys_vhangup(); /* should just do in sys_exit() */ int sys_vfork(); /* XXX - was awaiting fork w/ copy on write */ int sys_ovadvise(); /* awaiting new madvise */ int sys_indir(); /* indirect system call */ int sys_ustat(); /* System V compatibility */ int sys_owait(); /* should use wait4 interface */ int sys_owait3(); /* should use wait4 interface */ int sys_umount(); /* still more Sys V (and 4.2?) compatibility */ int sys_umount2(); int sys_pathconf(); /* posix */ int sys_fpathconf(); /* posix */ int sys_sysconf(); /* posix */ int sys_delete_module(); int sys_debug(); /* END JUNK */ int sys_vtrace(); /* kernel event tracing */ /* nfs */ int sys_async_daemon(); /* client async daemon */ int sys_nfs_svc(); /* run nfs server */ int sys_nfs_getfh(); /* get file handle */ int sys_exportfs(); /* export file systems */ int sys_rfssys(); /* RFS-related calls */ int sys_getmsg(); int sys_putmsg(); int sys_poll(); int sys_vpixsys(); /* VP/ix system calls */ int sys_sendfile64(), sys_futex(), sys_gettid(), sys_sched_setaffinity(); int sys_sched_getaffinity(), sys_setxattr(), sys_lsetxattr(); int sys_fsetxattr(), sys_getxattr(), sys_lgetxattr(), sys_fgetxattr(); int sys_listxattr(), sys_llistxattr(), sys_flistxattr(); int sys_removexattr(), sys_lremovexattr(), sys_fremovexattr(); int sys_remap_file_pages(), sys_readahead(), sys_tgkill(), sys_statfs64(); int sys_fstatfs64(), sys_clock_settime(), sys_clock_gettime(); int sys_clock_getres(), sys_clock_nanosleep(); int sys_timer_create(), sys_timer_settime(), sys_timer_gettime(); #include "syscall1.h"
CM-Archive/android_external_strace
ioctlsort.c
<filename>ioctlsort.c /* * Copyright (c) 1991, 1992 <NAME> <<EMAIL>> * Copyright (c) 1993, 1994, 1995 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: ioctlsort.c,v 1.2 2001/03/17 17:26:34 wichert Exp $ */ #include <stdio.h> #ifdef STDC_HEADERS #include <stdlib.h> #endif struct ioctlent { char *doth; char *symbol; unsigned long code; }; #include "ioctlent.raw" int nioctlents = sizeof ioctlent / sizeof ioctlent[0]; int compare(a, b) const void *a; const void *b; { unsigned long code1 = ((struct ioctlent *) a)->code; unsigned long code2 = ((struct ioctlent *) b)->code; return (code1 > code2) ? 1 : (code1 < code2) ? -1 : 0; } int main(argc, argv) int argc; char *argv[]; { int i; qsort(ioctlent, nioctlents, sizeof ioctlent[0], compare); for (i = 0; i < nioctlents; i++) { printf("{\"%s\", \"%s\", %#lx},\n", ioctlent[i].doth, ioctlent[i].symbol, ioctlent[i].code); } return 0; }
CM-Archive/android_external_strace
strace/linux/sparc/syscallent1.h
/* * Copyright (c) 1993, 1994, 1995, 1996 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: syscallent1.h,v 1.1.1.1 1999/02/19 00:23:19 wichert Exp $ */ { 6, 0, solaris_syscall, "syscall" }, /* 0 */ { 6, TP, solaris_exit, "_exit" }, /* 1 */ { 6, TP, solaris_fork, "fork" }, /* 2 */ { 6, 0, solaris_read, "read" }, /* 3 */ { 6, 0, solaris_write, "write" }, /* 4 */ { 6, TF, solaris_open, "open" }, /* 5 */ { 6, 0, solaris_close, "close" }, /* 6 */ { 6, TP, solaris_wait, "wait" }, /* 7 */ { 6, TF, solaris_creat, "creat" }, /* 8 */ { 6, TF, solaris_link, "link" }, /* 9 */ { 6, TF, solaris_unlink, "unlink" }, /* 10 */ { 6, TF|TP, solaris_exec, "exec" }, /* 11 */ { 6, TF, solaris_chdir, "chdir" }, /* 12 */ { 6, 0, solaris_time, "time" }, /* 13 */ { 6, TF, solaris_mknod, "mknod" }, /* 14 */ { 6, TF, solaris_chmod, "chmod" }, /* 15 */ { 6, TF, solaris_chown, "chown" }, /* 16 */ { 6, 0, solaris_brk, "brk" }, /* 17 */ { 6, TF, solaris_stat, "stat" }, /* 18 */ { 6, 0, solaris_lseek, "lseek" }, /* 19 */ { 6, 0, solaris_getpid, "getpid" }, /* 20 */ { 6, TF, solaris_mount, "mount" }, /* 21 */ { 6, TF, solaris_umount, "umount" }, /* 22 */ { 6, 0, solaris_setuid, "setuid" }, /* 23 */ { 6, 0, solaris_getuid, "getuid" }, /* 24 */ { 6, 0, solaris_stime, "stime" }, /* 25 */ { 6, 0, solaris_ptrace, "ptrace" }, /* 26 */ { 6, 0, solaris_alarm, "alarm" }, /* 27 */ { 6, 0, solaris_fstat, "fstat" }, /* 28 */ { 6, TS, solaris_pause, "pause" }, /* 29 */ { 6, TF, solaris_utime, "utime" }, /* 30 */ { 6, 0, solaris_stty, "stty" }, /* 31 */ { 6, 0, solaris_gtty, "gtty" }, /* 32 */ { 6, TF, solaris_access, "access" }, /* 33 */ { 6, 0, solaris_nice, "nice" }, /* 34 */ { 6, TF, solaris_statfs, "statfs" }, /* 35 */ { 6, 0, solaris_sync, "sync" }, /* 36 */ { 6, TS, solaris_kill, "kill" }, /* 37 */ { 6, 0, solaris_fstatfs, "fstatfs" }, /* 38 */ { 6, 0, solaris_pgrpsys, "pgrpsys" }, /* 39 */ { 6, 0, solaris_xenix, "xenix" }, /* 40 */ { 6, 0, solaris_dup, "dup" }, /* 41 */ { 6, 0, solaris_pipe, "pipe" }, /* 42 */ { 6, 0, solaris_times, "times" }, /* 43 */ { 6, 0, solaris_profil, "profil" }, /* 44 */ { 6, 0, solaris_plock, "plock" }, /* 45 */ { 6, 0, solaris_setgid, "setgid" }, /* 46 */ { 6, 0, solaris_getgid, "getgid" }, /* 47 */ { 6, 0, solaris_sigcall, "sigcall" }, /* 48 */ { 6, TI, solaris_msgsys, "msgsys" }, /* 49 */ { 6, 0, solaris_syssun, "syssun" }, /* 50 */ { 6, TF, solaris_acct, "acct" }, /* 51 */ { 6, TI, solaris_shmsys, "shmsys" }, /* 52 */ { 6, TI, solaris_semsys, "semsys" }, /* 53 */ { 6, 0, solaris_ioctl, "ioctl" }, /* 54 */ { 6, 0, solaris_uadmin, "uadmin" }, /* 55 */ { 6, 0, solaris_sysmp, "sysmp" }, /* 56 */ { 6, 0, solaris_utssys, "utssys" }, /* 57 */ { 6, 0, solaris_fdsync, "fdsync" }, /* 58 */ { 6, TF|TP, solaris_execve, "execve" }, /* 59 */ { 6, 0, solaris_umask, "umask" }, /* 60 */ { 6, TF, solaris_chroot, "chroot" }, /* 61 */ { 6, 0, solaris_fcntl, "fcntl" }, /* 62 */ { 6, 0, solaris_ulimit, "ulimit" }, /* 63 */ { 6, 0, printargs, "SYS_64" }, /* 64 */ { 6, 0, printargs, "SYS_65" }, /* 65 */ { 6, 0, printargs, "SYS_66" }, /* 66 */ { 6, 0, printargs, "SYS_67" }, /* 67 */ { 6, 0, printargs, "SYS_68" }, /* 68 */ { 6, 0, printargs, "SYS_69" }, /* 69 */ { 6, 0, printargs, "SYS_70" }, /* 70 */ { 6, 0, printargs, "SYS_71" }, /* 71 */ { 6, 0, printargs, "SYS_72" }, /* 72 */ { 6, 0, printargs, "SYS_73" }, /* 73 */ { 6, 0, printargs, "SYS_74" }, /* 74 */ { 6, 0, printargs, "SYS_75" }, /* 75 */ { 6, 0, printargs, "SYS_76" }, /* 76 */ { 6, 0, printargs, "SYS_77" }, /* 77 */ { 6, 0, printargs, "SYS_78" }, /* 78 */ { 6, TF, solaris_rmdir, "rmdir" }, /* 79 */ { 6, TF, solaris_mkdir, "mkdir" }, /* 80 */ { 6, 0, solaris_getdents, "getdents" }, /* 81 */ { 6, 0, solaris_sginap, "sginap" }, /* 82 */ { 6, 0, solaris_sgikopt, "sgikopt" }, /* 83 */ { 6, 0, solaris_sysfs, "sysfs" }, /* 84 */ { 6, TN, sys_getmsg, "getmsg" }, /* 85 */ { 6, TN, sys_putmsg, "putmsg" }, /* 86 */ { 6, TN, solaris_poll, "poll" }, /* 87 */ { 6, TF, solaris_lstat, "lstat" }, /* 88 */ { 6, TF, solaris_symlink, "symlink" }, /* 89 */ { 6, TF, solaris_readlink, "readlink" }, /* 90 */ { 6, 0, solaris_setgroups, "setgroups" }, /* 91 */ { 6, 0, solaris_getgroups, "getgroups" }, /* 92 */ { 6, 0, solaris_fchmod, "fchmod" }, /* 93 */ { 6, 0, solaris_fchown, "fchown" }, /* 94 */ { 6, TS, solaris_sigprocmask, "sigprocmask" }, /* 95 */ { 6, TS, solaris_sigsuspend, "sigsuspend" }, /* 96 */ { 6, TS, solaris_sigaltstack, "sigaltstack" }, /* 97 */ { 6, TS, solaris_sigaction, "sigaction" }, /* 98 */ { 6, 0, solaris_spcall, "spcall" }, /* 99 */ { 6, 0, solaris_context, "context" }, /* 100 */ { 6, 0, solaris_evsys, "evsys" }, /* 101 */ { 6, 0, solaris_evtrapret, "evtrapret" }, /* 102 */ { 6, TF, solaris_statvfs, "statvfs" }, /* 103 */ { 6, 0, solaris_fstatvfs, "fstatvfs" }, /* 104 */ { 6, 0, printargs, "SYS_105" }, /* 105 */ { 6, 0, solaris_nfssys, "nfssys" }, /* 106 */ { 6, TP, solaris_waitid, "waitid" }, /* 107 */ { 6, 0, solaris_sigsendsys, "sigsendsys" }, /* 108 */ { 6, 0, solaris_hrtsys, "hrtsys" }, /* 109 */ { 6, 0, solaris_acancel, "acancel" }, /* 110 */ { 6, 0, solaris_async, "async" }, /* 111 */ { 6, 0, solaris_priocntlsys, "priocntlsys" }, /* 112 */ { 6, TF, solaris_pathconf, "pathconf" }, /* 113 */ { 6, 0, solaris_mincore, "mincore" }, /* 114 */ { 6, 0, solaris_mmap, "mmap" }, /* 115 */ { 6, 0, solaris_mprotect, "mprotect" }, /* 116 */ { 6, 0, solaris_munmap, "munmap" }, /* 117 */ { 6, 0, solaris_fpathconf, "fpathconf" }, /* 118 */ { 6, TP, solaris_vfork, "vfork" }, /* 119 */ { 6, 0, solaris_fchdir, "fchdir" }, /* 120 */ { 6, 0, solaris_readv, "readv" }, /* 121 */ { 6, 0, solaris_writev, "writev" }, /* 122 */ { 6, TF, solaris_xstat, "xstat" }, /* 123 */ { 6, TF, solaris_lxstat, "lxstat" }, /* 124 */ { 6, 0, solaris_fxstat, "fxstat" }, /* 125 */ { 6, TF, solaris_xmknod, "xmknod" }, /* 126 */ { 6, 0, solaris_clocal, "clocal" }, /* 127 */ { 6, 0, solaris_setrlimit, "setrlimit" }, /* 128 */ { 6, 0, solaris_getrlimit, "getrlimit" }, /* 129 */ { 6, TF, solaris_lchown, "lchown" }, /* 130 */ { 6, 0, solaris_memcntl, "memcntl" }, /* 131 */ { 6, TN, solaris_getpmsg, "getpmsg" }, /* 132 */ { 6, TN, solaris_putpmsg, "putpmsg" }, /* 133 */ { 6, TF, solaris_rename, "rename" }, /* 134 */ { 6, 0, solaris_uname, "uname" }, /* 135 */ { 6, 0, solaris_setegid, "setegid" }, /* 136 */ { 6, 0, solaris_sysconfig, "sysconfig" }, /* 137 */ { 6, 0, solaris_adjtime, "adjtime" }, /* 138 */ { 6, 0, solaris_sysinfo, "sysinfo" }, /* 139 */ { 6, 0, printargs, "SYS_140" }, /* 140 */ { 6, 0, solaris_seteuid, "seteuid" }, /* 141 */ { 6, 0, solaris_vtrace, "vtrace" }, /* 142 */ { 6, TP, solaris_fork1, "fork1" }, /* 143 */ { 6, TS, solaris_sigtimedwait, "sigtimedwait" }, /* 144 */ { 6, 0, solaris_lwp_info, "lwp_info" }, /* 145 */ { 6, 0, solaris_yield, "yield" }, /* 146 */ { 6, 0, solaris_lwp_sema_wait, "lwp_sema_wait" }, /* 147 */ { 6, 0, solaris_lwp_sema_post, "lwp_sema_post" }, /* 148 */ { 6, 0, printargs, "SYS_149" }, /* 149 */ { 6, 0, printargs, "SYS_150" }, /* 150 */ { 6, 0, printargs, "SYS_151" }, /* 151 */ { 6, 0, solaris_modctl, "modctl" }, /* 152 */ { 6, 0, solaris_fchroot, "fchroot" }, /* 153 */ { 6, TF, solaris_utimes, "utimes" }, /* 154 */ { 6, 0, solaris_vhangup, "vhangup" }, /* 155 */ { 6, 0, solaris_gettimeofday, "gettimeofday" }, /* 156 */ { 6, 0, solaris_getitimer, "getitimer" }, /* 157 */ { 6, 0, solaris_setitimer, "setitimer" }, /* 158 */ { 6, 0, solaris_lwp_create, "lwp_create" }, /* 159 */ { 6, 0, solaris_lwp_exit, "lwp_exit" }, /* 160 */ { 6, 0, solaris_lwp_suspend, "lwp_suspend" }, /* 161 */ { 6, 0, solaris_lwp_continue, "lwp_continue" }, /* 162 */ { 6, 0, solaris_lwp_kill, "lwp_kill" }, /* 163 */ { 6, 0, solaris_lwp_self, "lwp_self" }, /* 164 */ { 6, 0, solaris_lwp_setprivate, "lwp_setprivate"}, /* 165 */ { 6, 0, solaris_lwp_getprivate, "lwp_getprivate"}, /* 166 */ { 6, 0, solaris_lwp_wait, "lwp_wait" }, /* 167 */ { 6, 0, solaris_lwp_mutex_unlock,"lwp_mutex_unlock"}, /* 168 */ { 6, 0, solaris_lwp_mutex_lock, "lwp_mutex_lock"}, /* 169 */ { 6, 0, solaris_lwp_cond_wait, "lwp_cond_wait"}, /* 170 */ { 6, 0, solaris_lwp_cond_signal,"lwp_cond_signal"}, /* 171 */ { 6, 0, solaris_lwp_cond_broadcast,"lwp_cond_broadcast"}, /* 172 */ { 6, 0, solaris_pread, "pread" }, /* 173 */ { 6, 0, solaris_pwrite, "pwrite" }, /* 174 */ { 6, 0, solaris_llseek, "llseek" }, /* 175 */ { 6, 0, solaris_inst_sync, "inst_sync" }, /* 176 */ { 6, 0, printargs, "SYS_177" }, /* 177 */ { 6, 0, printargs, "SYS_178" }, /* 178 */ { 6, 0, printargs, "SYS_179" }, /* 179 */ { 6, 0, printargs, "SYS_180" }, /* 180 */ { 6, 0, printargs, "SYS_181" }, /* 181 */ { 6, 0, printargs, "SYS_182" }, /* 182 */ { 6, 0, printargs, "SYS_183" }, /* 183 */ { 6, 0, printargs, "SYS_184" }, /* 184 */ { 6, 0, printargs, "SYS_185" }, /* 185 */ { 6, 0, solaris_auditsys, "auditsys" }, /* 186 */ { 6, 0, solaris_processor_bind, "processor_bind"}, /* 187 */ { 6, 0, solaris_processor_info, "processor_info"}, /* 188 */ { 6, 0, solaris_p_online, "p_online" }, /* 189 */ { 6, 0, solaris_sigqueue, "sigqueue" }, /* 190 */ { 6, 0, solaris_clock_gettime, "clock_gettime" }, /* 191 */ { 6, 0, solaris_clock_settime, "clock_settime" }, /* 192 */ { 6, 0, solaris_clock_getres, "clock_getres" }, /* 193 */ { 6, 0, solaris_timer_create, "timer_create" }, /* 194 */ { 6, 0, solaris_timer_delete, "timer_delete" }, /* 195 */ { 6, 0, solaris_timer_settime, "timer_settime" }, /* 196 */ { 6, 0, solaris_timer_gettime, "timer_gettime" }, /* 197 */ { 6, 0, solaris_timer_getoverrun,"timer_getoverrun"}, /* 198 */ { 6, 0, solaris_nanosleep, "nanosleep" }, /* 199 */ { 6, 0, printargs, "SYS_200" }, /* 200 */ { 6, 0, printargs, "SYS_201" }, /* 201 */ { 6, 0, printargs, "SYS_202" }, /* 202 */ { 6, 0, printargs, "SYS_203" }, /* 203 */ { 6, 0, printargs, "SYS_204" }, /* 204 */ { 6, 0, printargs, "SYS_205" }, /* 205 */ { 6, 0, printargs, "SYS_206" }, /* 206 */ { 6, 0, printargs, "SYS_207" }, /* 207 */ { 6, 0, printargs, "SYS_208" }, /* 208 */ { 6, 0, printargs, "SYS_209" }, /* 209 */ { 6, 0, printargs, "SYS_210" }, /* 210 */ { 6, 0, printargs, "SYS_211" }, /* 211 */ { 6, 0, printargs, "SYS_212" }, /* 212 */ { 6, 0, printargs, "SYS_213" }, /* 213 */ { 6, 0, printargs, "SYS_214" }, /* 214 */ { 6, 0, printargs, "SYS_215" }, /* 215 */ { 6, 0, printargs, "SYS_216" }, /* 216 */ { 6, 0, printargs, "SYS_217" }, /* 217 */ { 6, 0, printargs, "SYS_218" }, /* 218 */ { 6, 0, printargs, "SYS_219" }, /* 219 */ { 6, 0, printargs, "SYS_220" }, /* 220 */ { 6, 0, printargs, "SYS_221" }, /* 221 */ { 6, 0, printargs, "SYS_222" }, /* 222 */ { 6, 0, printargs, "SYS_223" }, /* 223 */ { 6, 0, printargs, "SYS_224" }, /* 224 */ { 6, 0, printargs, "SYS_225" }, /* 225 */ { 6, 0, printargs, "SYS_226" }, /* 226 */ { 6, 0, printargs, "SYS_227" }, /* 227 */ { 6, 0, printargs, "SYS_228" }, /* 228 */ { 6, 0, printargs, "SYS_229" }, /* 229 */ { 6, 0, printargs, "SYS_230" }, /* 230 */ { 6, 0, printargs, "SYS_231" }, /* 231 */ { 6, 0, printargs, "SYS_232" }, /* 232 */ { 6, 0, printargs, "SYS_233" }, /* 233 */ { 6, 0, printargs, "SYS_234" }, /* 234 */ { 6, 0, printargs, "SYS_235" }, /* 235 */ { 6, 0, printargs, "SYS_236" }, /* 236 */ { 6, 0, printargs, "SYS_237" }, /* 237 */ { 6, 0, printargs, "SYS_238" }, /* 238 */ { 6, 0, printargs, "SYS_239" }, /* 239 */ { 6, 0, printargs, "SYS_240" }, /* 240 */ { 6, 0, printargs, "SYS_241" }, /* 241 */ { 6, 0, printargs, "SYS_242" }, /* 242 */ { 6, 0, printargs, "SYS_243" }, /* 243 */ { 6, 0, printargs, "SYS_244" }, /* 244 */ { 6, 0, printargs, "SYS_245" }, /* 245 */ { 6, 0, printargs, "SYS_246" }, /* 246 */ { 6, 0, printargs, "SYS_247" }, /* 247 */ { 6, 0, printargs, "SYS_248" }, /* 248 */ { 6, 0, printargs, "SYS_249" }, /* 249 */ { 6, 0, printargs, "SYS_250" }, /* 250 */ { 6, 0, printargs, "SYS_251" }, /* 251 */ { 6, 0, printargs, "SYS_252" }, /* 252 */ { 6, 0, printargs, "SYS_253" }, /* 253 */ { 6, 0, printargs, "SYS_254" }, /* 254 */ { 6, 0, printargs, "SYS_255" }, /* 255 */ { 6, 0, printargs, "SYS_256" }, /* 256 */ { 6, 0, printargs, "SYS_257" }, /* 257 */ { 6, 0, printargs, "SYS_258" }, /* 258 */ { 6, 0, printargs, "SYS_259" }, /* 259 */ { 6, 0, printargs, "SYS_260" }, /* 260 */ { 6, 0, printargs, "SYS_261" }, /* 261 */ { 6, 0, printargs, "SYS_262" }, /* 262 */ { 6, 0, printargs, "SYS_263" }, /* 263 */ { 6, 0, printargs, "SYS_264" }, /* 264 */ { 6, 0, printargs, "SYS_265" }, /* 265 */ { 6, 0, printargs, "SYS_266" }, /* 266 */ { 6, 0, printargs, "SYS_267" }, /* 267 */ { 6, 0, printargs, "SYS_268" }, /* 268 */ { 6, 0, printargs, "SYS_269" }, /* 269 */ { 6, 0, printargs, "SYS_270" }, /* 270 */ { 6, 0, printargs, "SYS_271" }, /* 271 */ { 6, 0, printargs, "SYS_272" }, /* 272 */ { 6, 0, printargs, "SYS_273" }, /* 273 */ { 6, 0, printargs, "SYS_274" }, /* 274 */ { 6, 0, printargs, "SYS_275" }, /* 275 */ { 6, 0, printargs, "SYS_276" }, /* 276 */ { 6, 0, printargs, "SYS_277" }, /* 277 */ { 6, 0, printargs, "SYS_278" }, /* 278 */ { 6, 0, printargs, "SYS_279" }, /* 279 */ { 6, 0, printargs, "SYS_280" }, /* 280 */ { 6, 0, printargs, "SYS_281" }, /* 281 */ { 6, 0, printargs, "SYS_282" }, /* 282 */ { 6, 0, printargs, "SYS_283" }, /* 283 */ { 6, 0, printargs, "SYS_284" }, /* 284 */ { 6, 0, printargs, "SYS_285" }, /* 285 */ { 6, 0, printargs, "SYS_286" }, /* 286 */ { 6, 0, printargs, "SYS_287" }, /* 287 */ { 6, 0, printargs, "SYS_288" }, /* 288 */ { 6, 0, printargs, "SYS_289" }, /* 289 */ { 6, 0, printargs, "SYS_290" }, /* 290 */ { 6, 0, printargs, "SYS_291" }, /* 291 */ { 6, 0, printargs, "SYS_292" }, /* 292 */ { 6, 0, printargs, "SYS_293" }, /* 293 */ { 6, 0, printargs, "SYS_294" }, /* 294 */ { 6, 0, printargs, "SYS_295" }, /* 295 */ { 6, 0, printargs, "SYS_296" }, /* 296 */ { 6, 0, printargs, "SYS_297" }, /* 297 */ { 6, 0, printargs, "SYS_298" }, /* 298 */ { 6, 0, printargs, "SYS_299" }, /* 299 */ { 6, 0, solaris_getpgrp, "getpgrp" }, /* 300 */ { 6, 0, solaris_setpgrp, "setpgrp" }, /* 301 */ { 6, 0, solaris_getsid, "getsid" }, /* 302 */ { 6, 0, solaris_setsid, "setsid" }, /* 303 */ { 6, 0, solaris_getpgid, "getpgid" }, /* 304 */ { 6, 0, solaris_setpgid, "setpgid" }, /* 305 */ { 6, 0, printargs, "SYS_306" }, /* 306 */ { 6, 0, printargs, "SYS_307" }, /* 307 */ { 6, 0, printargs, "SYS_308" }, /* 308 */ { 6, 0, printargs, "SYS_309" }, /* 309 */ { 6, TS, solaris_signal, "signal" }, /* 310 */ { 6, TS, solaris_sigset, "sigset" }, /* 311 */ { 6, TS, solaris_sighold, "sighold" }, /* 312 */ { 6, TS, solaris_sigrelse, "sigrelse" }, /* 313 */ { 6, TS, solaris_sigignore, "sigignore" }, /* 314 */ { 6, TS, solaris_sigpause, "sigpause" }, /* 315 */ { 6, 0, printargs, "SYS_316" }, /* 316 */ { 6, 0, printargs, "SYS_317" }, /* 317 */ { 6, 0, printargs, "SYS_318" }, /* 318 */ { 6, 0, printargs, "SYS_319" }, /* 319 */ { 6, TI, solaris_msgget, "msgget" }, /* 320 */ { 6, TI, solaris_msgctl, "msgctl" }, /* 321 */ { 6, TI, solaris_msgrcv, "msgrcv" }, /* 322 */ { 6, TI, solaris_msgsnd, "msgsnd" }, /* 323 */ { 6, 0, printargs, "SYS_324" }, /* 324 */ { 6, 0, printargs, "SYS_325" }, /* 325 */ { 6, 0, printargs, "SYS_326" }, /* 326 */ { 6, 0, printargs, "SYS_327" }, /* 327 */ { 6, 0, printargs, "SYS_328" }, /* 328 */ { 6, 0, printargs, "SYS_329" }, /* 329 */ { 6, TI, solaris_shmat, "shmat" }, /* 330 */ { 6, TI, solaris_shmctl, "shmctl" }, /* 331 */ { 6, TI, solaris_shmdt, "shmdt" }, /* 332 */ { 6, TI, solaris_shmget, "shmget" }, /* 333 */ { 6, 0, printargs, "SYS_334" }, /* 334 */ { 6, 0, printargs, "SYS_335" }, /* 335 */ { 6, 0, printargs, "SYS_336" }, /* 336 */ { 6, 0, printargs, "SYS_337" }, /* 337 */ { 6, 0, printargs, "SYS_338" }, /* 338 */ { 6, 0, printargs, "SYS_339" }, /* 339 */ { 6, TI, solaris_semctl, "semctl" }, /* 340 */ { 6, TI, solaris_semget, "semget" }, /* 341 */ { 6, TI, solaris_semop, "semop" }, /* 342 */ { 6, 0, printargs, "SYS_343" }, /* 343 */ { 6, 0, printargs, "SYS_344" }, /* 344 */ { 6, 0, printargs, "SYS_345" }, /* 345 */ { 6, 0, printargs, "SYS_346" }, /* 346 */ { 6, 0, printargs, "SYS_347" }, /* 347 */ { 6, 0, printargs, "SYS_348" }, /* 348 */ { 6, 0, printargs, "SYS_349" }, /* 349 */ { 6, 0, solaris_olduname, "olduname" }, /* 350 */ { 6, 0, printargs, "utssys1" }, /* 351 */ { 6, 0, solaris_ustat, "ustat" }, /* 352 */ { 6, 0, solaris_fusers, "fusers" }, /* 353 */ { 6, 0, printargs, "SYS_354" }, /* 354 */ { 6, 0, printargs, "SYS_355" }, /* 355 */ { 6, 0, printargs, "SYS_356" }, /* 356 */ { 6, 0, printargs, "SYS_357" }, /* 357 */ { 6, 0, printargs, "SYS_358" }, /* 358 */ { 6, 0, printargs, "SYS_359" }, /* 359 */ { 6, 0, printargs, "sysfs0" }, /* 360 */ { 6, 0, solaris_sysfs1, "sysfs1" }, /* 361 */ { 6, 0, solaris_sysfs2, "sysfs2" }, /* 362 */ { 6, 0, solaris_sysfs3, "sysfs3" }, /* 363 */ { 6, 0, printargs, "SYS_364" }, /* 364 */ { 6, 0, printargs, "SYS_365" }, /* 365 */ { 6, 0, printargs, "SYS_366" }, /* 366 */ { 6, 0, printargs, "SYS_367" }, /* 367 */ { 6, 0, printargs, "SYS_368" }, /* 368 */ { 6, 0, printargs, "SYS_369" }, /* 369 */ { 6, 0, printargs, "spcall0" }, /* 370 */ { 6, TS, solaris_sigpending, "sigpending" }, /* 371 */ { 6, TS, solaris_sigfillset, "sigfillset" }, /* 372 */ { 6, 0, printargs, "SYS_373" }, /* 373 */ { 6, 0, printargs, "SYS_374" }, /* 374 */ { 6, 0, printargs, "SYS_375" }, /* 375 */ { 6, 0, printargs, "SYS_376" }, /* 376 */ { 6, 0, printargs, "SYS_377" }, /* 377 */ { 6, 0, printargs, "SYS_378" }, /* 378 */ { 6, 0, printargs, "SYS_379" }, /* 379 */ { 6, 0, solaris_getcontext, "getcontext" }, /* 380 */ { 6, 0, solaris_setcontext, "setcontext" }, /* 381 */ { 6, 0, printargs, "SYS_382" }, /* 382 */ { 6, 0, printargs, "SYS_383" }, /* 383 */ { 6, 0, printargs, "SYS_384" }, /* 384 */ { 6, 0, printargs, "SYS_385" }, /* 385 */ { 6, 0, printargs, "SYS_386" }, /* 386 */ { 6, 0, printargs, "SYS_387" }, /* 387 */ { 6, 0, printargs, "SYS_388" }, /* 388 */ { 6, 0, printargs, "SYS_389" }, /* 389 */ { 6, 0, printargs, "SYS_390" }, /* 390 */ { 6, 0, printargs, "SYS_391" }, /* 391 */ { 6, 0, printargs, "SYS_392" }, /* 392 */ { 6, 0, printargs, "SYS_393" }, /* 393 */ { 6, 0, printargs, "SYS_394" }, /* 394 */ { 6, 0, printargs, "SYS_395" }, /* 395 */ { 6, 0, printargs, "SYS_396" }, /* 396 */ { 6, 0, printargs, "SYS_397" }, /* 397 */ { 6, 0, printargs, "SYS_398" }, /* 398 */ { 6, 0, printargs, "SYS_399" }, /* 399 */
CM-Archive/android_external_strace
io.c
<reponame>CM-Archive/android_external_strace /* * Copyright (c) 1991, 1992 <NAME> <<EMAIL>> * Copyright (c) 1993 <NAME> <<EMAIL>> * Copyright (c) 1993, 1994, 1995, 1996 <NAME> <<EMAIL>> * Copyright (c) 1996-1999 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: io.c,v 1.20 2005/06/01 19:22:08 roland Exp $ */ #include "defs.h" #include <fcntl.h> #if HAVE_SYS_UIO_H #include <sys/uio.h> #endif #ifdef HAVE_LONG_LONG_OFF_T /* * Hacks for systems that have a long long off_t */ #define sys_pread64 sys_pread #define sys_pwrite64 sys_pwrite #endif int sys_read(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); } else { if (syserror(tcp)) tprintf("%#lx", tcp->u_arg[1]); else printstr(tcp, tcp->u_arg[1], tcp->u_rval); tprintf(", %lu", tcp->u_arg[2]); } return 0; } int sys_write(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); printstr(tcp, tcp->u_arg[1], tcp->u_arg[2]); tprintf(", %lu", tcp->u_arg[2]); } return 0; } #if HAVE_SYS_UIO_H void tprint_iov(tcp, len, addr) struct tcb * tcp; unsigned long len; unsigned long addr; { #if defined(LINUX) && SUPPORTED_PERSONALITIES > 1 union { struct { u_int32_t base; u_int32_t len; } iov32; struct { u_int64_t base; u_int64_t len; } iov64; } iov; #define sizeof_iov \ (personality_wordsize[current_personality] == 4 \ ? sizeof(iov.iov32) : sizeof(iov.iov64)) #define iov_iov_base \ (personality_wordsize[current_personality] == 4 \ ? (u_int64_t) iov.iov32.base : iov.iov64.base) #define iov_iov_len \ (personality_wordsize[current_personality] == 4 \ ? (u_int64_t) iov.iov32.len : iov.iov64.len) #else struct iovec iov; #define sizeof_iov sizeof(iov) #define iov_iov_base iov.iov_base #define iov_iov_len iov.iov_len #endif unsigned long size, cur, end, abbrev_end; int failed = 0; if (!len) { tprintf("[]"); return; } size = len * sizeof_iov; end = addr + size; if (!verbose(tcp) || size / sizeof_iov != len || end < addr) { tprintf("%#lx", addr); return; } if (abbrev(tcp)) { abbrev_end = addr + max_strlen * sizeof_iov; if (abbrev_end < addr) abbrev_end = end; } else { abbrev_end = end; } tprintf("["); for (cur = addr; cur < end; cur += sizeof_iov) { if (cur > addr) tprintf(", "); if (cur >= abbrev_end) { tprintf("..."); break; } if (umoven(tcp, cur, sizeof_iov, (char *) &iov) < 0) { tprintf("?"); failed = 1; break; } tprintf("{"); printstr(tcp, (long) iov_iov_base, iov_iov_len); tprintf(", %lu}", (unsigned long)iov_iov_len); } tprintf("]"); if (failed) tprintf(" %#lx", addr); #undef sizeof_iov #undef iov_iov_base #undef iov_iov_len } int sys_readv(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); } else { if (syserror(tcp)) { tprintf("%#lx, %lu", tcp->u_arg[1], tcp->u_arg[2]); return 0; } tprint_iov(tcp, tcp->u_arg[2], tcp->u_arg[1]); tprintf(", %lu", tcp->u_arg[2]); } return 0; } int sys_writev(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); tprint_iov(tcp, tcp->u_arg[2], tcp->u_arg[1]); tprintf(", %lu", tcp->u_arg[2]); } return 0; } #endif #if defined(SVR4) int sys_pread(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); } else { if (syserror(tcp)) tprintf("%#lx", tcp->u_arg[1]); else printstr(tcp, tcp->u_arg[1], tcp->u_rval); #if UNIXWARE /* off_t is signed int */ tprintf(", %lu, %ld", tcp->u_arg[2], tcp->u_arg[3]); #else tprintf(", %lu, %llu", tcp->u_arg[2], LONG_LONG(tcp->u_arg[3], tcp->u_arg[4])); #endif } return 0; } int sys_pwrite(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); printstr(tcp, tcp->u_arg[1], tcp->u_arg[2]); #if UNIXWARE /* off_t is signed int */ tprintf(", %lu, %ld", tcp->u_arg[2], tcp->u_arg[3]); #else tprintf(", %lu, %llu", tcp->u_arg[2], LONG_LONG(tcp->u_arg[3], tcp->u_arg[4])); #endif } return 0; } #endif /* SVR4 */ #ifdef FREEBSD #include <sys/types.h> #include <sys/socket.h> int sys_sendfile(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, %ld, %llu, %lu", tcp->u_arg[0], tcp->u_arg[1], LONG_LONG(tcp->u_arg[2], tcp->u_arg[3]), tcp->u_arg[4]); } else { off_t offset; if (!tcp->u_arg[5]) tprintf(", NULL"); else { struct sf_hdtr hdtr; if (umove(tcp, tcp->u_arg[5], &hdtr) < 0) tprintf(", %#lx", tcp->u_arg[5]); else { tprintf(", { "); tprint_iov(tcp, hdtr.hdr_cnt, hdtr.headers); tprintf(", %u, ", hdtr.hdr_cnt); tprint_iov(tcp, hdtr.trl_cnt, hdtr.trailers); tprintf(", %u }", hdtr.hdr_cnt); } } if (!tcp->u_arg[6]) tprintf(", NULL"); else if (umove(tcp, tcp->u_arg[6], &offset) < 0) tprintf(", %#lx", tcp->u_arg[6]); else tprintf(", [%llu]", offset); tprintf(", %lu", tcp->u_arg[7]); } return 0; } #endif /* FREEBSD */ #ifdef LINUX /* The SH4 ABI does allow long longs in odd-numbered registers, but does not allow them to be split between registers and memory - and there are only four argument registers for normal functions. As a result pread takes an extra padding argument before the offset. This was changed late in the 2.4 series (around 2.4.20). */ #if defined(SH) #define PREAD_OFFSET_ARG 4 #else #define PREAD_OFFSET_ARG 3 #endif int sys_pread(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); } else { if (syserror(tcp)) tprintf("%#lx", tcp->u_arg[1]); else printstr(tcp, tcp->u_arg[1], tcp->u_rval); ALIGN64 (tcp, PREAD_OFFSET_ARG); /* PowerPC alignment restriction */ tprintf(", %lu, %llu", tcp->u_arg[2], *(unsigned long long *)&tcp->u_arg[PREAD_OFFSET_ARG]); } return 0; } int sys_pwrite(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); printstr(tcp, tcp->u_arg[1], tcp->u_arg[2]); ALIGN64 (tcp, PREAD_OFFSET_ARG); /* PowerPC alignment restriction */ tprintf(", %lu, %llu", tcp->u_arg[2], *(unsigned long long *)&tcp->u_arg[PREAD_OFFSET_ARG]); } return 0; } int sys_sendfile(tcp) struct tcb *tcp; { if (entering(tcp)) { off_t offset; tprintf("%ld, %ld, ", tcp->u_arg[0], tcp->u_arg[1]); if (!tcp->u_arg[2]) tprintf("NULL"); else if (umove(tcp, tcp->u_arg[2], &offset) < 0) tprintf("%#lx", tcp->u_arg[2]); else tprintf("[%lu]", offset); tprintf(", %lu", tcp->u_arg[3]); } return 0; } int sys_sendfile64(tcp) struct tcb *tcp; { if (entering(tcp)) { loff_t offset; tprintf("%ld, %ld, ", tcp->u_arg[0], tcp->u_arg[1]); if (!tcp->u_arg[2]) tprintf("NULL"); else if (umove(tcp, tcp->u_arg[2], &offset) < 0) tprintf("%#lx", tcp->u_arg[2]); else tprintf("[%llu]", (unsigned long long int) offset); tprintf(", %lu", tcp->u_arg[3]); } return 0; } #endif /* LINUX */ #if _LFS64_LARGEFILE || HAVE_LONG_LONG_OFF_T int sys_pread64(tcp) struct tcb *tcp; { if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); } else { ALIGN64 (tcp, 3); if (syserror(tcp)) tprintf("%#lx", tcp->u_arg[1]); else printstr(tcp, tcp->u_arg[1], tcp->u_rval); tprintf(", %lu, %#llx", tcp->u_arg[2], LONG_LONG(tcp->u_arg[3], tcp->u_arg[4])); } return 0; } int sys_pwrite64(tcp) struct tcb *tcp; { if (entering(tcp)) { ALIGN64 (tcp, 3); tprintf("%ld, ", tcp->u_arg[0]); printstr(tcp, tcp->u_arg[1], tcp->u_arg[2]); tprintf(", %lu, %#llx", tcp->u_arg[2], LONG_LONG(tcp->u_arg[3], tcp->u_arg[4])); } return 0; } #endif int sys_ioctl(tcp) struct tcb *tcp; { const struct ioctlent *iop; if (entering(tcp)) { tprintf("%ld, ", tcp->u_arg[0]); iop = ioctl_lookup(tcp->u_arg[1]); if (iop) { tprintf("%s", iop->symbol); while ((iop = ioctl_next_match(iop))) tprintf(" or %s", iop->symbol); } else tprintf("%#lx", tcp->u_arg[1]); ioctl_decode(tcp, tcp->u_arg[1], tcp->u_arg[2]); } else { int ret; if (!(ret = ioctl_decode(tcp, tcp->u_arg[1], tcp->u_arg[2]))) tprintf(", %#lx", tcp->u_arg[2]); else return ret - 1; } return 0; }
CM-Archive/android_external_strace
syscall.c
/* * Copyright (c) 1991, 1992 <NAME> <<EMAIL>> * Copyright (c) 1993 <NAME> <<EMAIL>> * Copyright (c) 1993, 1994, 1995, 1996 <NAME> <<EMAIL>> * Copyright (c) 1996-1999 <NAME> <<EMAIL>> * Copyright (c) 1999 IBM Deutschland Entwicklung GmbH, IBM Corporation * Linux for s390 port by <NAME> * <<EMAIL>,<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: syscall.c,v 1.79 2005/06/08 20:45:28 roland Exp $ */ #include "defs.h" #include <signal.h> #include <time.h> #include <errno.h> #ifndef HAVE_ANDROID_OS #include <sys/user.h> #endif #include <sys/syscall.h> #include <sys/param.h> #if HAVE_ASM_REG_H #if defined (SPARC) || defined (SPARC64) # define fpq kernel_fpq # define fq kernel_fq # define fpu kernel_fpu #endif #include <asm/reg.h> #if defined (SPARC) || defined (SPARC64) # undef fpq # undef fq # undef fpu #endif #endif #ifdef HAVE_SYS_REG_H #include <sys/reg.h> #ifndef PTRACE_PEEKUSR # define PTRACE_PEEKUSR PTRACE_PEEKUSER #endif #elif defined(HAVE_LINUX_PTRACE_H) #undef PTRACE_SYSCALL # ifdef HAVE_STRUCT_IA64_FPREG # define ia64_fpreg XXX_ia64_fpreg # endif # ifdef HAVE_STRUCT_PT_ALL_USER_REGS # define pt_all_user_regs XXX_pt_all_user_regs # endif #include <linux/ptrace.h> # undef ia64_fpreg # undef pt_all_user_regs #endif #if defined (LINUX) && defined (SPARC64) # define r_pc r_tpc # undef PTRACE_GETREGS # define PTRACE_GETREGS PTRACE_GETREGS64 # undef PTRACE_SETREGS # define PTRACE_SETREGS PTRACE_SETREGS64 #endif /* LINUX && SPARC64 */ #if defined(LINUX) && defined(IA64) # include <asm/ptrace_offsets.h> # include <asm/rse.h> #endif #define NR_SYSCALL_BASE 0 #ifdef LINUX #ifndef ERESTARTSYS #define ERESTARTSYS 512 #endif #ifndef ERESTARTNOINTR #define ERESTARTNOINTR 513 #endif #ifndef ERESTARTNOHAND #define ERESTARTNOHAND 514 /* restart if no handler.. */ #endif #ifndef ENOIOCTLCMD #define ENOIOCTLCMD 515 /* No ioctl command */ #endif #ifndef ERESTART_RESTARTBLOCK #define ERESTART_RESTARTBLOCK 516 /* restart by calling sys_restart_syscall */ #endif #ifndef NSIG #define NSIG 32 #endif #ifdef ARM #undef NSIG #define NSIG 32 #undef NR_SYSCALL_BASE #define NR_SYSCALL_BASE __NR_SYSCALL_BASE #endif #endif /* LINUX */ #include "syscall-android.h" #include "syscall.h" /* Define these shorthand notations to simplify the syscallent files. */ #define TF TRACE_FILE #define TI TRACE_IPC #define TN TRACE_NETWORK #define TP TRACE_PROCESS #define TS TRACE_SIGNAL static const struct sysent sysent0[] = { #include "syscallent.h" }; static const int nsyscalls0 = sizeof sysent0 / sizeof sysent0[0]; int qual_flags0[MAX_QUALS]; #if SUPPORTED_PERSONALITIES >= 2 static const struct sysent sysent1[] = { #include "syscallent1.h" }; static const int nsyscalls1 = sizeof sysent1 / sizeof sysent1[0]; int qual_flags1[MAX_QUALS]; #endif /* SUPPORTED_PERSONALITIES >= 2 */ #if SUPPORTED_PERSONALITIES >= 3 static const struct sysent sysent2[] = { #include "syscallent2.h" }; static const int nsyscalls2 = sizeof sysent2 / sizeof sysent2[0]; int qual_flags2[MAX_QUALS]; #endif /* SUPPORTED_PERSONALITIES >= 3 */ const struct sysent *sysent; int *qual_flags; int nsyscalls; /* Now undef them since short defines cause wicked namespace pollution. */ #undef TF #undef TI #undef TN #undef TP #undef TS static const char *const errnoent0[] = { #include "errnoent.h" }; static const int nerrnos0 = sizeof errnoent0 / sizeof errnoent0[0]; #if SUPPORTED_PERSONALITIES >= 2 static const char *const errnoent1[] = { #include "errnoent1.h" }; static const int nerrnos1 = sizeof errnoent1 / sizeof errnoent1[0]; #endif /* SUPPORTED_PERSONALITIES >= 2 */ #if SUPPORTED_PERSONALITIES >= 3 static const char *const errnoent2[] = { #include "errnoent2.h" }; static const int nerrnos2 = sizeof errnoent2 / sizeof errnoent2[0]; #endif /* SUPPORTED_PERSONALITIES >= 3 */ const char *const *errnoent; int nerrnos; int current_personality; #ifndef PERSONALITY0_WORDSIZE # define PERSONALITY0_WORDSIZE sizeof(long) #endif const int personality_wordsize[SUPPORTED_PERSONALITIES] = { PERSONALITY0_WORDSIZE, #if SUPPORTED_PERSONALITIES > 1 PERSONALITY1_WORDSIZE, #endif #if SUPPORTED_PERSONALITIES > 2 PERSONALITY2_WORDSIZE, #endif };; int set_personality(personality) int personality; { switch (personality) { case 0: errnoent = errnoent0; nerrnos = nerrnos0; sysent = sysent0; nsyscalls = nsyscalls0; ioctlent = ioctlent0; nioctlents = nioctlents0; signalent = signalent0; nsignals = nsignals0; qual_flags = qual_flags0; break; #if SUPPORTED_PERSONALITIES >= 2 case 1: errnoent = errnoent1; nerrnos = nerrnos1; sysent = sysent1; nsyscalls = nsyscalls1; ioctlent = ioctlent1; nioctlents = nioctlents1; signalent = signalent1; nsignals = nsignals1; qual_flags = qual_flags1; break; #endif /* SUPPORTED_PERSONALITIES >= 2 */ #if SUPPORTED_PERSONALITIES >= 3 case 2: errnoent = errnoent2; nerrnos = nerrnos2; sysent = sysent2; nsyscalls = nsyscalls2; ioctlent = ioctlent2; nioctlents = nioctlents2; signalent = signalent2; nsignals = nsignals2; qual_flags = qual_flags2; break; #endif /* SUPPORTED_PERSONALITIES >= 3 */ default: return -1; } current_personality = personality; return 0; } struct call_counts { struct timeval time; int calls, errors; }; static struct call_counts *counts; static struct timeval shortest = { 1000000, 0 }; static int qual_syscall(), qual_signal(), qual_fault(), qual_desc(); static const struct qual_options { int bitflag; char *option_name; int (*qualify)(); char *argument_name; } qual_options[] = { { QUAL_TRACE, "trace", qual_syscall, "system call" }, { QUAL_TRACE, "t", qual_syscall, "system call" }, { QUAL_ABBREV, "abbrev", qual_syscall, "system call" }, { QUAL_ABBREV, "a", qual_syscall, "system call" }, { QUAL_VERBOSE, "verbose", qual_syscall, "system call" }, { QUAL_VERBOSE, "v", qual_syscall, "system call" }, { QUAL_RAW, "raw", qual_syscall, "system call" }, { QUAL_RAW, "x", qual_syscall, "system call" }, { QUAL_SIGNAL, "signal", qual_signal, "signal" }, { QUAL_SIGNAL, "signals", qual_signal, "signal" }, { QUAL_SIGNAL, "s", qual_signal, "signal" }, { QUAL_FAULT, "fault", qual_fault, "fault" }, { QUAL_FAULT, "faults", qual_fault, "fault" }, { QUAL_FAULT, "m", qual_fault, "fault" }, { QUAL_READ, "read", qual_desc, "descriptor" }, { QUAL_READ, "reads", qual_desc, "descriptor" }, { QUAL_READ, "r", qual_desc, "descriptor" }, { QUAL_WRITE, "write", qual_desc, "descriptor" }, { QUAL_WRITE, "writes", qual_desc, "descriptor" }, { QUAL_WRITE, "w", qual_desc, "descriptor" }, { 0, NULL, NULL, NULL }, }; static void qualify_one(n, opt, not, pers) int n; const struct qual_options *opt; int not; int pers; { if (pers == 0 || pers < 0) { if (not) qual_flags0[n] &= ~opt->bitflag; else qual_flags0[n] |= opt->bitflag; } #if SUPPORTED_PERSONALITIES >= 2 if (pers == 1 || pers < 0) { if (not) qual_flags1[n] &= ~opt->bitflag; else qual_flags1[n] |= opt->bitflag; } #endif /* SUPPORTED_PERSONALITIES >= 2 */ #if SUPPORTED_PERSONALITIES >= 3 if (pers == 2 || pers < 0) { if (not) qual_flags2[n] &= ~opt->bitflag; else qual_flags2[n] |= opt->bitflag; } #endif /* SUPPORTED_PERSONALITIES >= 3 */ } static int qual_syscall(s, opt, not) char *s; const struct qual_options *opt; int not; { int i; int rc = -1; if (isdigit((unsigned char)*s)) { int i = atoi(s); if (i < 0 || i >= MAX_QUALS) return -1; qualify_one(i, opt, not, -1); return 0; } for (i = 0; i < nsyscalls0; i++) if (strcmp(s, sysent0[i].sys_name) == 0) { qualify_one(i, opt, not, 0); rc = 0; } #if SUPPORTED_PERSONALITIES >= 2 for (i = 0; i < nsyscalls1; i++) if (strcmp(s, sysent1[i].sys_name) == 0) { qualify_one(i, opt, not, 1); rc = 0; } #endif /* SUPPORTED_PERSONALITIES >= 2 */ #if SUPPORTED_PERSONALITIES >= 3 for (i = 0; i < nsyscalls2; i++) if (strcmp(s, sysent2[i].sys_name) == 0) { qualify_one(i, opt, not, 2); rc = 0; } #endif /* SUPPORTED_PERSONALITIES >= 3 */ return rc; } static int qual_signal(s, opt, not) char *s; const struct qual_options *opt; int not; { int i; char buf[32]; if (isdigit((unsigned char)*s)) { int signo = atoi(s); if (signo < 0 || signo >= MAX_QUALS) return -1; qualify_one(signo, opt, not, -1); return 0; } if (strlen(s) >= sizeof buf) return -1; strcpy(buf, s); s = buf; for (i = 0; s[i]; i++) s[i] = toupper((unsigned char)(s[i])); if (strncmp(s, "SIG", 3) == 0) s += 3; for (i = 0; i <= NSIG; i++) if (strcmp(s, signame(i) + 3) == 0) { qualify_one(i, opt, not, -1); return 0; } return -1; } static int qual_fault(s, opt, not) char *s; const struct qual_options *opt; int not; { return -1; } static int qual_desc(s, opt, not) char *s; const struct qual_options *opt; int not; { if (isdigit((unsigned char)*s)) { int desc = atoi(s); if (desc < 0 || desc >= MAX_QUALS) return -1; qualify_one(desc, opt, not, -1); return 0; } return -1; } static int lookup_class(s) char *s; { if (strcmp(s, "file") == 0) return TRACE_FILE; if (strcmp(s, "ipc") == 0) return TRACE_IPC; if (strcmp(s, "network") == 0) return TRACE_NETWORK; if (strcmp(s, "process") == 0) return TRACE_PROCESS; if (strcmp(s, "signal") == 0) return TRACE_SIGNAL; return -1; } void qualify(s) char *s; { const struct qual_options *opt; int not; char *p; int i, n; opt = &qual_options[0]; for (i = 0; (p = qual_options[i].option_name); i++) { n = strlen(p); if (strncmp(s, p, n) == 0 && s[n] == '=') { opt = &qual_options[i]; s += n + 1; break; } } not = 0; if (*s == '!') { not = 1; s++; } if (strcmp(s, "none") == 0) { not = 1 - not; s = "all"; } if (strcmp(s, "all") == 0) { for (i = 0; i < MAX_QUALS; i++) { qualify_one(i, opt, not, -1); } return; } for (i = 0; i < MAX_QUALS; i++) { qualify_one(i, opt, !not, -1); } for (p = strtok(s, ","); p; p = strtok(NULL, ",")) { if (opt->bitflag == QUAL_TRACE && (n = lookup_class(p)) > 0) { for (i = 0; i < nsyscalls0; i++) if (sysent0[i].sys_flags & n) qualify_one(i, opt, not, 0); #if SUPPORTED_PERSONALITIES >= 2 for (i = 0; i < nsyscalls1; i++) if (sysent1[i].sys_flags & n) qualify_one(i, opt, not, 1); #endif /* SUPPORTED_PERSONALITIES >= 2 */ #if SUPPORTED_PERSONALITIES >= 3 for (i = 0; i < nsyscalls2; i++) if (sysent2[i].sys_flags & n) qualify_one(i, opt, not, 2); #endif /* SUPPORTED_PERSONALITIES >= 3 */ continue; } if (opt->qualify(p, opt, not)) { fprintf(stderr, "strace: invalid %s `%s'\n", opt->argument_name, p); exit(1); } } return; } static void dumpio(tcp) struct tcb *tcp; { if (syserror(tcp)) return; if (tcp->u_arg[0] < 0 || tcp->u_arg[0] >= MAX_QUALS) return; switch (known_scno(tcp)) { case SYS_read: #ifdef SYS_pread64 case SYS_pread64: #endif #if defined SYS_pread && SYS_pread64 != SYS_pread case SYS_pread: #endif #ifdef SYS_recv case SYS_recv: #elif defined SYS_sub_recv case SYS_sub_recv: #endif #ifdef SYS_recvfrom case SYS_recvfrom: #elif defined SYS_sub_recvfrom case SYS_sub_recvfrom: #endif if (qual_flags[tcp->u_arg[0]] & QUAL_READ) dumpstr(tcp, tcp->u_arg[1], tcp->u_rval); break; case SYS_write: #ifdef SYS_pwrite64 case SYS_pwrite64: #endif #if defined SYS_pwrite && SYS_pwrite64 != SYS_pwrite case SYS_pwrite: #endif #ifdef SYS_send case SYS_send: #elif defined SYS_sub_send case SYS_sub_send: #endif #ifdef SYS_sendto case SYS_sendto: #elif defined SYS_sub_sendto case SYS_sub_sendto: #endif if (qual_flags[tcp->u_arg[0]] & QUAL_WRITE) dumpstr(tcp, tcp->u_arg[1], tcp->u_arg[2]); break; #ifdef SYS_readv case SYS_readv: if (qual_flags[tcp->u_arg[0]] & QUAL_READ) dumpiov(tcp, tcp->u_arg[2], tcp->u_arg[1]); break; #endif #ifdef SYS_writev case SYS_writev: if (qual_flags[tcp->u_arg[0]] & QUAL_WRITE) dumpiov(tcp, tcp->u_arg[2], tcp->u_arg[1]); break; #endif } } #ifndef FREEBSD enum subcall_style { shift_style, deref_style, mask_style, door_style }; #else /* FREEBSD */ enum subcall_style { shift_style, deref_style, mask_style, door_style, table_style }; struct subcall { int call; int nsubcalls; int subcalls[5]; }; static const struct subcall subcalls_table[] = { { SYS_shmsys, 5, { SYS_shmat, SYS_shmctl, SYS_shmdt, SYS_shmget, SYS_shmctl } }, #ifdef SYS_semconfig { SYS_semsys, 4, { SYS___semctl, SYS_semget, SYS_semop, SYS_semconfig } }, #else { SYS_semsys, 3, { SYS___semctl, SYS_semget, SYS_semop } }, #endif { SYS_msgsys, 4, { SYS_msgctl, SYS_msgget, SYS_msgsnd, SYS_msgrcv } }, }; #endif /* FREEBSD */ #if !(defined(LINUX) && ( defined(ALPHA) || defined(MIPS) )) static const int socket_map [] = { /* SYS_SOCKET */ 97, /* SYS_BIND */ 104, /* SYS_CONNECT */ 98, /* SYS_LISTEN */ 106, /* SYS_ACCEPT */ 99, /* SYS_GETSOCKNAME */ 150, /* SYS_GETPEERNAME */ 141, /* SYS_SOCKETPAIR */ 135, /* SYS_SEND */ 101, /* SYS_RECV */ 102, /* SYS_SENDTO */ 133, /* SYS_RECVFROM */ 125, /* SYS_SHUTDOWN */ 134, /* SYS_SETSOCKOPT */ 105, /* SYS_GETSOCKOPT */ 118, /* SYS_SENDMSG */ 114, /* SYS_RECVMSG */ 113 }; #if defined (SPARC) || defined (SPARC64) static void sparc_socket_decode (tcp) struct tcb *tcp; { volatile long addr; volatile int i, n; if (tcp->u_arg [0] < 1 || tcp->u_arg [0] > sizeof(socket_map)/sizeof(int)+1){ return; } tcp->scno = socket_map [tcp->u_arg [0]-1]; n = tcp->u_nargs = sysent [tcp->scno].nargs; addr = tcp->u_arg [1]; for (i = 0; i < n; i++){ int arg; if (umoven (tcp, addr, sizeof (arg), (void *) &arg) < 0) arg = 0; tcp->u_arg [i] = arg; addr += sizeof (arg); } } #endif static void decode_subcall(tcp, subcall, nsubcalls, style) struct tcb *tcp; int subcall; int nsubcalls; enum subcall_style style; { unsigned long addr, mask; int i; int size = personality_wordsize[current_personality]; switch (style) { case shift_style: if (tcp->u_arg[0] < 0 || tcp->u_arg[0] >= nsubcalls) return; tcp->scno = subcall + tcp->u_arg[0]; if (sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs--; for (i = 0; i < tcp->u_nargs; i++) tcp->u_arg[i] = tcp->u_arg[i + 1]; break; case deref_style: if (tcp->u_arg[0] < 0 || tcp->u_arg[0] >= nsubcalls) return; tcp->scno = subcall + tcp->u_arg[0]; addr = tcp->u_arg[1]; for (i = 0; i < sysent[tcp->scno].nargs; i++) { if (size == sizeof(int)) { unsigned int arg; if (umove(tcp, addr, &arg) < 0) arg = 0; tcp->u_arg[i] = arg; } else if (size == sizeof(long)) { unsigned long arg; if (umove(tcp, addr, &arg) < 0) arg = 0; tcp->u_arg[i] = arg; } else abort(); addr += size; } tcp->u_nargs = sysent[tcp->scno].nargs; break; case mask_style: mask = (tcp->u_arg[0] >> 8) & 0xff; for (i = 0; mask; i++) mask >>= 1; if (i >= nsubcalls) return; tcp->u_arg[0] &= 0xff; tcp->scno = subcall + i; if (sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; break; case door_style: /* * Oh, yuck. The call code is the *sixth* argument. * (don't you mean the *last* argument? - JH) */ if (tcp->u_arg[5] < 0 || tcp->u_arg[5] >= nsubcalls) return; tcp->scno = subcall + tcp->u_arg[5]; if (sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs--; break; #ifdef FREEBSD case table_style: for (i = 0; i < sizeof(subcalls_table) / sizeof(struct subcall); i++) if (subcalls_table[i].call == tcp->scno) break; if (i < sizeof(subcalls_table) / sizeof(struct subcall) && tcp->u_arg[0] >= 0 && tcp->u_arg[0] < subcalls_table[i].nsubcalls) { tcp->scno = subcalls_table[i].subcalls[tcp->u_arg[0]]; for (i = 0; i < tcp->u_nargs; i++) tcp->u_arg[i] = tcp->u_arg[i + 1]; } break; #endif /* FREEBSD */ } } #endif struct tcb *tcp_last = NULL; static int internal_syscall(tcp) struct tcb *tcp; { /* * We must always trace a few critical system calls in order to * correctly support following forks in the presence of tracing * qualifiers. */ switch (known_scno(tcp)) { #ifdef SYS_fork case SYS_fork: #endif #ifdef SYS_vfork case SYS_vfork: #endif #ifdef SYS_fork1 case SYS_fork1: #endif #ifdef SYS_forkall case SYS_forkall: #endif #ifdef SYS_rfork1 case SYS_rfork1: #endif #ifdef SYS_rforkall case SYS_rforkall: #endif #ifdef SYS_rfork case SYS_rfork: #endif internal_fork(tcp); break; #ifdef SYS_clone case SYS_clone: internal_clone(tcp); break; #endif #ifdef SYS_clone2 case SYS_clone2: internal_clone(tcp); break; #endif #ifdef SYS_execv case SYS_execv: #endif #ifdef SYS_execve case SYS_execve: #endif #ifdef SYS_rexecve case SYS_rexecve: #endif internal_exec(tcp); break; #ifdef SYS_wait case SYS_wait: #endif #ifdef SYS_wait4 case SYS_wait4: #endif #ifdef SYS32_wait4 case SYS32_wait4: #endif #ifdef SYS_waitpid case SYS_waitpid: #endif #ifdef SYS_waitsys case SYS_waitsys: #endif internal_wait(tcp, 2); break; #ifdef SYS_waitid case SYS_waitid: internal_wait(tcp, 3); break; #endif #ifdef SYS_exit case SYS_exit: #endif #ifdef SYS32_exit case SYS32_exit: #endif #ifdef __NR_exit_group case __NR_exit_group: #endif #ifdef IA64 case 252: /* IA-32 __NR_exit_group */ #endif internal_exit(tcp); break; } return 0; } #ifdef LINUX #if defined (I386) static long eax; #elif defined (IA64) long r8, r10, psr; long ia32 = 0; #elif defined (POWERPC) static long result,flags; #elif defined (M68K) static int d0; #elif defined (ARM) static struct pt_regs regs; #elif defined (ALPHA) static long r0; static long a3; #elif defined (SPARC) || defined (SPARC64) static struct regs regs; static unsigned long trap; #elif defined(MIPS) static long a3; static long r2; #elif defined(S390) || defined(S390X) static long gpr2; static long pc; static long syscall_mode; #elif defined(HPPA) static long r28; #elif defined(SH) static long r0; #elif defined(SH64) static long r9; #elif defined(X86_64) static long rax; #endif #endif /* LINUX */ #ifdef FREEBSD struct reg regs; #endif /* FREEBSD */ int get_scno(tcp) struct tcb *tcp; { long scno = 0; #ifndef USE_PROCFS int pid = tcp->pid; #endif /* !PROCFS */ #ifdef LINUX #if defined(S390) || defined(S390X) if (tcp->flags & TCB_WAITEXECVE) { /* * When the execve system call completes successfully, the * new process still has -ENOSYS (old style) or __NR_execve * (new style) in gpr2. We cannot recover the scno again * by disassembly, because the image that executed the * syscall is gone now. Fortunately, we don't want it. We * leave the flag set so that syscall_fixup can fake the * result. */ if (tcp->flags & TCB_INSYSCALL) return 1; /* * This is the SIGTRAP after execve. We cannot try to read * the system call here either. */ tcp->flags &= ~TCB_WAITEXECVE; return 0; } if (upeek(pid, PT_GPR2, &syscall_mode) < 0) return -1; if (syscall_mode != -ENOSYS) { /* * Since kernel version 2.5.44 the scno gets passed in gpr2. */ scno = syscall_mode; } else { /* * Old style of "passing" the scno via the SVC instruction. */ long opcode, offset_reg, tmp; void * svc_addr; int gpr_offset[16] = {PT_GPR0, PT_GPR1, PT_ORIGGPR2, PT_GPR3, PT_GPR4, PT_GPR5, PT_GPR6, PT_GPR7, PT_GPR8, PT_GPR9, PT_GPR10, PT_GPR11, PT_GPR12, PT_GPR13, PT_GPR14, PT_GPR15}; if (upeek(pid, PT_PSWADDR, &pc) < 0) return -1; errno = 0; opcode = ptrace(PTRACE_PEEKTEXT, pid, (char *)(pc-sizeof(long)), 0); if (errno) { perror("peektext(pc-oneword)"); return -1; } /* * We have to check if the SVC got executed directly or via an * EXECUTE instruction. In case of EXECUTE it is necessary to do * instruction decoding to derive the system call number. * Unfortunately the opcode sizes of EXECUTE and SVC are differently, * so that this doesn't work if a SVC opcode is part of an EXECUTE * opcode. Since there is no way to find out the opcode size this * is the best we can do... */ if ((opcode & 0xff00) == 0x0a00) { /* SVC opcode */ scno = opcode & 0xff; } else { /* SVC got executed by EXECUTE instruction */ /* * Do instruction decoding of EXECUTE. If you really want to * understand this, read the Principles of Operations. */ svc_addr = (void *) (opcode & 0xfff); tmp = 0; offset_reg = (opcode & 0x000f0000) >> 16; if (offset_reg && (upeek(pid, gpr_offset[offset_reg], &tmp) < 0)) return -1; svc_addr += tmp; tmp = 0; offset_reg = (opcode & 0x0000f000) >> 12; if (offset_reg && (upeek(pid, gpr_offset[offset_reg], &tmp) < 0)) return -1; svc_addr += tmp; scno = ptrace(PTRACE_PEEKTEXT, pid, svc_addr, 0); if (errno) return -1; #if defined(S390X) scno >>= 48; #else scno >>= 16; #endif tmp = 0; offset_reg = (opcode & 0x00f00000) >> 20; if (offset_reg && (upeek(pid, gpr_offset[offset_reg], &tmp) < 0)) return -1; scno = (scno | tmp) & 0xff; } } #elif defined (POWERPC) if (upeek(pid, sizeof(unsigned long)*PT_R0, &scno) < 0) return -1; if (!(tcp->flags & TCB_INSYSCALL)) { /* Check if we return from execve. */ if (scno == 0 && (tcp->flags & TCB_WAITEXECVE)) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } } #elif defined (I386) if (upeek(pid, 4*ORIG_EAX, &scno) < 0) return -1; #elif defined (X86_64) if (upeek(pid, 8*ORIG_RAX, &scno) < 0) return -1; if (!(tcp->flags & TCB_INSYSCALL)) { static int currpers=-1; long val; /* Check CS register value. On x86-64 linux it is: * 0x33 for long mode (64 bit) * 0x23 for compatibility mode (32 bit) * It takes only one ptrace and thus doesn't need * to be cached. */ if (upeek(pid, 8*CS, &val) < 0) return -1; switch(val) { case 0x23: currpers = 1; break; case 0x33: currpers = 0; break; default: fprintf(stderr, "Unknown value CS=0x%02X while " "detecting personality of process " "PID=%d\n", (int)val, pid); currpers = current_personality; break; } #if 0 /* This version analyzes the opcode of a syscall instruction. * (int 0x80 on i386 vs. syscall on x86-64) * It works, but is too complicated. */ unsigned long val, rip, i; if(upeek(pid, 8*RIP, &rip)<0) perror("upeek(RIP)"); /* sizeof(syscall) == sizeof(int 0x80) == 2 */ rip-=2; errno = 0; call = ptrace(PTRACE_PEEKTEXT,pid,(char *)rip,0); if (errno) printf("ptrace_peektext failed: %s\n", strerror(errno)); switch (call & 0xffff) { /* x86-64: syscall = 0x0f 0x05 */ case 0x050f: currpers = 0; break; /* i386: int 0x80 = 0xcd 0x80 */ case 0x80cd: currpers = 1; break; default: currpers = current_personality; fprintf(stderr, "Unknown syscall opcode (0x%04X) while " "detecting personality of process " "PID=%d\n", (int)call, pid); break; } #endif if(currpers != current_personality) { char *names[]={"64 bit", "32 bit"}; set_personality(currpers); printf("[ Process PID=%d runs in %s mode. ]\n", pid, names[current_personality]); } } #elif defined(IA64) # define IA64_PSR_IS ((long)1 << 34) if (upeek (pid, PT_CR_IPSR, &psr) >= 0) ia32 = (psr & IA64_PSR_IS) != 0; if (!(tcp->flags & TCB_INSYSCALL)) { if (ia32) { if (upeek(pid, PT_R1, &scno) < 0) /* orig eax */ return -1; } else { if (upeek (pid, PT_R15, &scno) < 0) return -1; } /* Check if we return from execve. */ if (tcp->flags & TCB_WAITEXECVE) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } } else { /* syscall in progress */ if (upeek (pid, PT_R8, &r8) < 0) return -1; if (upeek (pid, PT_R10, &r10) < 0) return -1; } #elif defined (ARM) /* * Read complete register set in one go. */ if (ptrace(PTRACE_GETREGS, pid, NULL, (void *)&regs) == -1) return -1; /* * We only need to grab the syscall number on syscall entry. */ if (regs.ARM_ip == 0) { if (!(tcp->flags & TCB_INSYSCALL)) { /* Check if we return from execve. */ if (tcp->flags & TCB_WAITEXECVE) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } } /* * Note: we only deal with only 32-bit CPUs here. */ if (regs.ARM_cpsr & 0x20) { /* * Get the Thumb-mode system call number */ scno = regs.ARM_r7; } else { /* * Get the ARM-mode system call number */ errno = 0; scno = ptrace(PTRACE_PEEKTEXT, pid, (void *)(regs.ARM_pc - 4), NULL); if (errno) return -1; if (scno == 0 && (tcp->flags & TCB_WAITEXECVE)) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } /* Handle the EABI syscall convention. We do not bother converting structures between the two ABIs, but basic functionality should work even if strace and the traced program have different ABIs. */ if (scno == 0xef000000) { scno = regs.ARM_r7; } else { if ((scno & 0x0ff00000) != 0x0f900000) { fprintf(stderr, "syscall: unknown syscall trap 0x%08lx\n", scno); return -1; } /* * Fixup the syscall number */ scno &= 0x000fffff; } } if (tcp->flags & TCB_INSYSCALL) { fprintf(stderr, "pid %d stray syscall entry\n", tcp->pid); tcp->flags &= ~TCB_INSYSCALL; } } else { if (!(tcp->flags & TCB_INSYSCALL)) { fprintf(stderr, "pid %d stray syscall exit\n", tcp->pid); tcp->flags |= TCB_INSYSCALL; } } #elif defined (M68K) if (upeek(pid, 4*PT_ORIG_D0, &scno) < 0) return -1; #elif defined (MIPS) if (upeek(pid, REG_A3, &a3) < 0) return -1; if(!(tcp->flags & TCB_INSYSCALL)) { if (upeek(pid, REG_V0, &scno) < 0) return -1; if (scno < 0 || scno > nsyscalls) { if(a3 == 0 || a3 == -1) { if(debug) fprintf (stderr, "stray syscall exit: v0 = %ld\n", scno); return 0; } } } else { if (upeek(pid, REG_V0, &r2) < 0) return -1; } #elif defined (ALPHA) if (upeek(pid, REG_A3, &a3) < 0) return -1; if (!(tcp->flags & TCB_INSYSCALL)) { if (upeek(pid, REG_R0, &scno) < 0) return -1; /* Check if we return from execve. */ if (scno == 0 && tcp->flags & TCB_WAITEXECVE) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } /* * Do some sanity checks to figure out if it's * really a syscall entry */ if (scno < 0 || scno > nsyscalls) { if (a3 == 0 || a3 == -1) { if (debug) fprintf (stderr, "stray syscall exit: r0 = %ld\n", scno); return 0; } } } else { if (upeek(pid, REG_R0, &r0) < 0) return -1; } #elif defined (SPARC) || defined (SPARC64) /* Everything we need is in the current register set. */ if (ptrace(PTRACE_GETREGS,pid,(char *)&regs,0) < 0) return -1; /* If we are entering, then disassemble the syscall trap. */ if (!(tcp->flags & TCB_INSYSCALL)) { /* Retrieve the syscall trap instruction. */ errno = 0; trap = ptrace(PTRACE_PEEKTEXT,pid,(char *)regs.r_pc,0); #if defined(SPARC64) trap >>= 32; #endif if (errno) return -1; /* Disassemble the trap to see what personality to use. */ switch (trap) { case 0x91d02010: /* Linux/SPARC syscall trap. */ set_personality(0); break; case 0x91d0206d: /* Linux/SPARC64 syscall trap. */ set_personality(2); break; case 0x91d02000: /* SunOS syscall trap. (pers 1) */ fprintf(stderr,"syscall: SunOS no support\n"); return -1; case 0x91d02008: /* Solaris 2.x syscall trap. (per 2) */ set_personality(1); break; case 0x91d02009: /* NetBSD/FreeBSD syscall trap. */ fprintf(stderr,"syscall: NetBSD/FreeBSD not supported\n"); return -1; case 0x91d02027: /* Solaris 2.x gettimeofday */ set_personality(1); break; default: /* Unknown syscall trap. */ if(tcp->flags & TCB_WAITEXECVE) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } #if defined (SPARC64) fprintf(stderr,"syscall: unknown syscall trap %08lx %016lx\n", trap, regs.r_tpc); #else fprintf(stderr,"syscall: unknown syscall trap %08x %08x\n", trap, regs.r_pc); #endif return -1; } /* Extract the system call number from the registers. */ if (trap == 0x91d02027) scno = 156; else scno = regs.r_g1; if (scno == 0) { scno = regs.r_o0; memmove (&regs.r_o0, &regs.r_o1, 7*sizeof(regs.r_o0)); } } #elif defined(HPPA) if (upeek(pid, PT_GR20, &scno) < 0) return -1; if (!(tcp->flags & TCB_INSYSCALL)) { /* Check if we return from execve. */ if ((tcp->flags & TCB_WAITEXECVE)) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } } #elif defined(SH) /* * In the new syscall ABI, the system call number is in R3. */ if (upeek(pid, 4*(REG_REG0+3), &scno) < 0) return -1; if (scno < 0) { /* Odd as it may seem, a glibc bug has been known to cause glibc to issue bogus negative syscall numbers. So for our purposes, make strace print what it *should* have been */ long correct_scno = (scno & 0xff); if (debug) fprintf(stderr, "Detected glibc bug: bogus system call number = %ld, " "correcting to %ld\n", scno, correct_scno); scno = correct_scno; } if (!(tcp->flags & TCB_INSYSCALL)) { /* Check if we return from execve. */ if (scno == 0 && tcp->flags & TCB_WAITEXECVE) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } } #elif defined(SH64) if (upeek(pid, REG_SYSCALL, &scno) < 0) return -1; scno &= 0xFFFF; if (!(tcp->flags & TCB_INSYSCALL)) { /* Check if we return from execve. */ if (tcp->flags & TCB_WAITEXECVE) { tcp->flags &= ~TCB_WAITEXECVE; return 0; } } #endif /* SH64 */ #endif /* LINUX */ #ifdef SUNOS4 if (upeek(pid, uoff(u_arg[7]), &scno) < 0) return -1; #elif defined(SH) /* new syscall ABI returns result in R0 */ if (upeek(pid, 4*REG_REG0, (long *)&r0) < 0) return -1; #elif defined(SH64) /* ABI defines result returned in r9 */ if (upeek(pid, REG_GENERAL(9), (long *)&r9) < 0) return -1; #endif #ifdef USE_PROCFS #ifdef HAVE_PR_SYSCALL scno = tcp->status.PR_SYSCALL; #else /* !HAVE_PR_SYSCALL */ #ifndef FREEBSD scno = tcp->status.PR_WHAT; #else /* FREEBSD */ if (pread(tcp->pfd_reg, &regs, sizeof(regs), 0) < 0) { perror("pread"); return -1; } switch (regs.r_eax) { case SYS_syscall: case SYS___syscall: pread(tcp->pfd, &scno, sizeof(scno), regs.r_esp + sizeof(int)); break; default: scno = regs.r_eax; break; } #endif /* FREEBSD */ #endif /* !HAVE_PR_SYSCALL */ #endif /* USE_PROCFS */ if (!(tcp->flags & TCB_INSYSCALL)) tcp->scno = scno; return 1; } long known_scno(tcp) struct tcb *tcp; { long scno = tcp->scno; if (scno >= 0 && scno < nsyscalls && sysent[scno].native_scno != 0) scno = sysent[scno].native_scno; else scno += NR_SYSCALL_BASE; return scno; } static int syscall_fixup(tcp) struct tcb *tcp; { #ifndef USE_PROCFS int pid = tcp->pid; #else /* USE_PROCFS */ int scno = known_scno(tcp); if (!(tcp->flags & TCB_INSYSCALL)) { if (tcp->status.PR_WHY != PR_SYSENTRY) { if ( scno == SYS_fork #ifdef SYS_vfork || scno == SYS_vfork #endif /* SYS_vfork */ #ifdef SYS_fork1 || scno == SYS_fork1 #endif /* SYS_fork1 */ #ifdef SYS_forkall || scno == SYS_forkall #endif /* SYS_forkall */ #ifdef SYS_rfork1 || scno == SYS_rfork1 #endif /* SYS_fork1 */ #ifdef SYS_rforkall || scno == SYS_rforkall #endif /* SYS_rforkall */ ) { /* We are returning in the child, fake it. */ tcp->status.PR_WHY = PR_SYSENTRY; trace_syscall(tcp); tcp->status.PR_WHY = PR_SYSEXIT; } else { fprintf(stderr, "syscall: missing entry\n"); tcp->flags |= TCB_INSYSCALL; } } } else { if (tcp->status.PR_WHY != PR_SYSEXIT) { fprintf(stderr, "syscall: missing exit\n"); tcp->flags &= ~TCB_INSYSCALL; } } #endif /* USE_PROCFS */ #ifdef SUNOS4 if (!(tcp->flags & TCB_INSYSCALL)) { if (scno == 0) { fprintf(stderr, "syscall: missing entry\n"); tcp->flags |= TCB_INSYSCALL; } } else { if (scno != 0) { if (debug) { /* * This happens when a signal handler * for a signal which interrupted a * a system call makes another system call. */ fprintf(stderr, "syscall: missing exit\n"); } tcp->flags &= ~TCB_INSYSCALL; } } #endif /* SUNOS4 */ #ifdef LINUX #if defined (I386) if (upeek(pid, 4*EAX, &eax) < 0) return -1; if (eax != -ENOSYS && !(tcp->flags & TCB_INSYSCALL)) { if (debug) fprintf(stderr, "stray syscall exit: eax = %ld\n", eax); return 0; } #elif defined (X86_64) if (upeek(pid, 8*RAX, &rax) < 0) return -1; if (current_personality == 1) rax = (long int)(int)rax; /* sign extend from 32 bits */ if (rax != -ENOSYS && !(tcp->flags & TCB_INSYSCALL)) { if (debug) fprintf(stderr, "stray syscall exit: rax = %ld\n", rax); return 0; } #elif defined (S390) || defined (S390X) if (upeek(pid, PT_GPR2, &gpr2) < 0) return -1; if (syscall_mode != -ENOSYS) syscall_mode = tcp->scno; if (gpr2 != syscall_mode && !(tcp->flags & TCB_INSYSCALL)) { if (debug) fprintf(stderr, "stray syscall exit: gpr2 = %ld\n", gpr2); return 0; } else if (((tcp->flags & (TCB_INSYSCALL|TCB_WAITEXECVE)) == (TCB_INSYSCALL|TCB_WAITEXECVE)) && (gpr2 == -ENOSYS || gpr2 == tcp->scno)) { /* * Fake a return value of zero. We leave the TCB_WAITEXECVE * flag set for the post-execve SIGTRAP to see and reset. */ gpr2 = 0; } #elif defined (POWERPC) # define SO_MASK 0x10000000 if (upeek(pid, sizeof(unsigned long)*PT_CCR, &flags) < 0) return -1; if (upeek(pid, sizeof(unsigned long)*PT_R3, &result) < 0) return -1; if (flags & SO_MASK) result = -result; #elif defined (M68K) if (upeek(pid, 4*PT_D0, &d0) < 0) return -1; if (d0 != -ENOSYS && !(tcp->flags & TCB_INSYSCALL)) { if (debug) fprintf(stderr, "stray syscall exit: d0 = %ld\n", d0); return 0; } #elif defined (ARM) /* * Nothing required */ #elif defined (HPPA) if (upeek(pid, PT_GR28, &r28) < 0) return -1; #elif defined(IA64) if (upeek(pid, PT_R10, &r10) < 0) return -1; if (upeek(pid, PT_R8, &r8) < 0) return -1; if (ia32 && r8 != -ENOSYS && !(tcp->flags & TCB_INSYSCALL)) { if (debug) fprintf(stderr, "stray syscall exit: r8 = %ld\n", r8); return 0; } #endif #endif /* LINUX */ return 1; } static int get_error(tcp) struct tcb *tcp; { int u_error = 0; #ifdef LINUX #if defined(S390) || defined(S390X) if (gpr2 && (unsigned) -gpr2 < nerrnos) { tcp->u_rval = -1; u_error = -gpr2; } else { tcp->u_rval = gpr2; u_error = 0; } #else /* !S390 && !S390X */ #ifdef I386 if (eax < 0 && -eax < nerrnos) { tcp->u_rval = -1; u_error = -eax; } else { tcp->u_rval = eax; u_error = 0; } #else /* !I386 */ #ifdef X86_64 if (rax < 0 && -rax < nerrnos) { tcp->u_rval = -1; u_error = -rax; } else { tcp->u_rval = rax; u_error = 0; } #else #ifdef IA64 if (ia32) { int err; err = (int)r8; if (err < 0 && -err < nerrnos) { tcp->u_rval = -1; u_error = -err; } else { tcp->u_rval = err; u_error = 0; } } else { if (r10) { tcp->u_rval = -1; u_error = r8; } else { tcp->u_rval = r8; u_error = 0; } } #else /* !IA64 */ #ifdef MIPS if (a3) { tcp->u_rval = -1; u_error = r2; } else { tcp->u_rval = r2; u_error = 0; } #else #ifdef POWERPC if (result && (unsigned long) -result < nerrnos) { tcp->u_rval = -1; u_error = -result; } else { tcp->u_rval = result; u_error = 0; } #else /* !POWERPC */ #ifdef M68K if (d0 && (unsigned) -d0 < nerrnos) { tcp->u_rval = -1; u_error = -d0; } else { tcp->u_rval = d0; u_error = 0; } #else /* !M68K */ #ifdef ARM if (regs.ARM_r0 && (unsigned) -regs.ARM_r0 < nerrnos) { tcp->u_rval = -1; u_error = -regs.ARM_r0; } else { tcp->u_rval = regs.ARM_r0; u_error = 0; } #else /* !ARM */ #ifdef ALPHA if (a3) { tcp->u_rval = -1; u_error = r0; } else { tcp->u_rval = r0; u_error = 0; } #else /* !ALPHA */ #ifdef SPARC if (regs.r_psr & PSR_C) { tcp->u_rval = -1; u_error = regs.r_o0; } else { tcp->u_rval = regs.r_o0; u_error = 0; } #else /* !SPARC */ #ifdef SPARC64 if (regs.r_tstate & 0x1100000000UL) { tcp->u_rval = -1; u_error = regs.r_o0; } else { tcp->u_rval = regs.r_o0; u_error = 0; } #else /* !SPARC64 */ #ifdef HPPA if (r28 && (unsigned) -r28 < nerrnos) { tcp->u_rval = -1; u_error = -r28; } else { tcp->u_rval = r28; u_error = 0; } #else #ifdef SH /* interpret R0 as return value or error number */ if (r0 && (unsigned) -r0 < nerrnos) { tcp->u_rval = -1; u_error = -r0; } else { tcp->u_rval = r0; u_error = 0; } #else #ifdef SH64 /* interpret result as return value or error number */ if (r9 && (unsigned) -r9 < nerrnos) { tcp->u_rval = -1; u_error = -r9; } else { tcp->u_rval = r9; u_error = 0; } #endif /* SH64 */ #endif /* SH */ #endif /* HPPA */ #endif /* SPARC */ #endif /* SPARC64 */ #endif /* ALPHA */ #endif /* ARM */ #endif /* M68K */ #endif /* POWERPC */ #endif /* MIPS */ #endif /* IA64 */ #endif /* X86_64 */ #endif /* I386 */ #endif /* S390 || S390X */ #endif /* LINUX */ #ifdef SUNOS4 /* get error code from user struct */ if (upeek(pid, uoff(u_error), &u_error) < 0) return -1; u_error >>= 24; /* u_error is a char */ /* get system call return value */ if (upeek(pid, uoff(u_rval1), &tcp->u_rval) < 0) return -1; #endif /* SUNOS4 */ #ifdef SVR4 #ifdef SPARC /* Judicious guessing goes a long way. */ if (tcp->status.pr_reg[R_PSR] & 0x100000) { tcp->u_rval = -1; u_error = tcp->status.pr_reg[R_O0]; } else { tcp->u_rval = tcp->status.pr_reg[R_O0]; u_error = 0; } #endif /* SPARC */ #ifdef I386 /* Wanna know how to kill an hour single-stepping? */ if (tcp->status.PR_REG[EFL] & 0x1) { tcp->u_rval = -1; u_error = tcp->status.PR_REG[EAX]; } else { tcp->u_rval = tcp->status.PR_REG[EAX]; #ifdef HAVE_LONG_LONG tcp->u_lrval = ((unsigned long long) tcp->status.PR_REG[EDX] << 32) + tcp->status.PR_REG[EAX]; #endif u_error = 0; } #endif /* I386 */ #ifdef X86_64 /* Wanna know how to kill an hour single-stepping? */ if (tcp->status.PR_REG[EFLAGS] & 0x1) { tcp->u_rval = -1; u_error = tcp->status.PR_REG[RAX]; } else { tcp->u_rval = tcp->status.PR_REG[RAX]; u_error = 0; } #endif /* X86_64 */ #ifdef MIPS if (tcp->status.pr_reg[CTX_A3]) { tcp->u_rval = -1; u_error = tcp->status.pr_reg[CTX_V0]; } else { tcp->u_rval = tcp->status.pr_reg[CTX_V0]; u_error = 0; } #endif /* MIPS */ #endif /* SVR4 */ #ifdef FREEBSD if (regs.r_eflags & PSL_C) { tcp->u_rval = -1; u_error = regs.r_eax; } else { tcp->u_rval = regs.r_eax; tcp->u_lrval = ((unsigned long long) regs.r_edx << 32) + regs.r_eax; u_error = 0; } #endif /* FREEBSD */ tcp->u_error = u_error; return 1; } int force_result(tcp, error, rval) struct tcb *tcp; int error; long rval; { #ifdef LINUX #if defined(S390) || defined(S390X) gpr2 = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)PT_GPR2, gpr2) < 0) return -1; #else /* !S390 && !S390X */ #ifdef I386 eax = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(EAX * 4), eax) < 0) return -1; #else /* !I386 */ #ifdef X86_64 rax = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(RAX * 8), rax) < 0) return -1; #else #ifdef IA64 if (ia32) { r8 = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(PT_R8), r8) < 0) return -1; } else { if (error) { r8 = error; r10 = -1; } else { r8 = rval; r10 = 0; } if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(PT_R8), r8) < 0 || ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(PT_R10), r10) < 0) return -1; } #else /* !IA64 */ #ifdef MIPS if (error) { r2 = error; a3 = -1; } else { r2 = rval; a3 = 0; } if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(REG_A3), a3) < 0 || ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(REG_V0), r2) < 0) return -1; #else #ifdef POWERPC if (upeek(tcp->pid, sizeof(unsigned long)*PT_CCR, &flags) < 0) return -1; if (error) { flags |= SO_MASK; result = error; } else { flags &= ~SO_MASK; result = rval; } if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(sizeof(unsigned long)*PT_CCR), flags) < 0 || ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(sizeof(unsigned long)*PT_R3), result) < 0) return -1; #else /* !POWERPC */ #ifdef M68K d0 = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(4*PT_D0), d0) < 0) return -1; #else /* !M68K */ #ifdef ARM regs.ARM_r0 = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(4*0), regs.ARM_r0) < 0) return -1; #else /* !ARM */ #ifdef ALPHA if (error) { a3 = -1; r0 = error; } else { a3 = 0; r0 = rval; } if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(REG_A3), a3) < 0 || ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(REG_R0), r0) < 0) return -1; #else /* !ALPHA */ #ifdef SPARC if (ptrace(PTRACE_GETREGS, tcp->pid, (char *)&regs, 0) < 0) return -1; if (error) { regs.r_psr |= PSR_C; regs.r_o0 = error; } else { regs.r_psr &= ~PSR_C; regs.r_o0 = rval; } if (ptrace(PTRACE_SETREGS, tcp->pid, (char *)&regs, 0) < 0) return -1; #else /* !SPARC */ #ifdef SPARC64 if (ptrace(PTRACE_GETREGS, tcp->pid, (char *)&regs, 0) < 0) return -1; if (error) { regs.r_tstate |= 0x1100000000UL; regs.r_o0 = error; } else { regs.r_tstate &= ~0x1100000000UL; regs.r_o0 = rval; } if (ptrace(PTRACE_SETREGS, tcp->pid, (char *)&regs, 0) < 0) return -1; #else /* !SPARC64 */ #ifdef HPPA r28 = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(PT_GR28), r28) < 0) return -1; #else #ifdef SH r0 = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(4*REG_REG0), r0) < 0) return -1; #else #ifdef SH64 r9 = error ? -error : rval; if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)REG_GENERAL(9), r9) < 0) return -1; #endif /* SH64 */ #endif /* SH */ #endif /* HPPA */ #endif /* SPARC */ #endif /* SPARC64 */ #endif /* ALPHA */ #endif /* ARM */ #endif /* M68K */ #endif /* POWERPC */ #endif /* MIPS */ #endif /* IA64 */ #endif /* X86_64 */ #endif /* I386 */ #endif /* S390 || S390X */ #endif /* LINUX */ #ifdef SUNOS4 if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)uoff(u_error), error << 24) < 0 || ptrace(PTRACE_POKEUSER, tcp->pid, (char*)uoff(u_rval1), rval) < 0) return -1; #endif /* SUNOS4 */ #ifdef SVR4 /* XXX no clue */ return -1; #endif /* SVR4 */ #ifdef FREEBSD if (pread(tcp->pfd_reg, &regs, sizeof(regs), 0) < 0) { perror("pread"); return -1; } if (error) { regs.r_eflags |= PSL_C; regs.r_eax = error; } else { regs.r_eflags &= ~PSL_C; regs.r_eax = rval; } if (pwrite(tcp->pfd_reg, &regs, sizeof(regs), 0) < 0) { perror("pwrite"); return -1; } #endif /* FREEBSD */ /* All branches reach here on success (only). */ tcp->u_error = error; tcp->u_rval = rval; return 0; } static int syscall_enter(tcp) struct tcb *tcp; { #ifndef USE_PROCFS int pid = tcp->pid; #endif /* !USE_PROCFS */ #ifdef LINUX #if defined(S390) || defined(S390X) { int i; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) { if (upeek(pid,i==0 ? PT_ORIGGPR2:PT_GPR2+i*sizeof(long), &tcp->u_arg[i]) < 0) return -1; } } #elif defined (ALPHA) { int i; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) { /* WTA: if scno is out-of-bounds this will bomb. Add range-check * for scno somewhere above here! */ if (upeek(pid, REG_A0+i, &tcp->u_arg[i]) < 0) return -1; } } #elif defined (IA64) { if (!ia32) { unsigned long *out0, *rbs_end, cfm, sof, sol, i; /* be backwards compatible with kernel < 2.4.4... */ # ifndef PT_RBS_END # define PT_RBS_END PT_AR_BSP # endif if (upeek(pid, PT_RBS_END, (long *) &rbs_end) < 0) return -1; if (upeek(pid, PT_CFM, (long *) &cfm) < 0) return -1; sof = (cfm >> 0) & 0x7f; sol = (cfm >> 7) & 0x7f; out0 = ia64_rse_skip_regs(rbs_end, -sof + sol); if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; ++i) { if (umoven(tcp, (unsigned long) ia64_rse_skip_regs(out0, i), sizeof(long), (char *) &tcp->u_arg[i]) < 0) return -1; } } else { int i; if (/* EBX = out0 */ upeek(pid, PT_R11, (long *) &tcp->u_arg[0]) < 0 /* ECX = out1 */ || upeek(pid, PT_R9, (long *) &tcp->u_arg[1]) < 0 /* EDX = out2 */ || upeek(pid, PT_R10, (long *) &tcp->u_arg[2]) < 0 /* ESI = out3 */ || upeek(pid, PT_R14, (long *) &tcp->u_arg[3]) < 0 /* EDI = out4 */ || upeek(pid, PT_R15, (long *) &tcp->u_arg[4]) < 0 /* EBP = out5 */ || upeek(pid, PT_R13, (long *) &tcp->u_arg[5]) < 0) return -1; for (i = 0; i < 6; ++i) /* truncate away IVE sign-extension */ tcp->u_arg[i] &= 0xffffffff; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = 5; } } #elif defined (MIPS) { long sp; int i, nargs; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) nargs = tcp->u_nargs = sysent[tcp->scno].nargs; else nargs = tcp->u_nargs = MAX_ARGS; if(nargs > 4) { if(upeek(pid, REG_SP, &sp) < 0) return -1; for(i = 0; i < 4; i++) { if (upeek(pid, REG_A0 + i, &tcp->u_arg[i])<0) return -1; } umoven(tcp, sp+16, (nargs-4) * sizeof(tcp->u_arg[0]), (char *)(tcp->u_arg + 4)); } else { for(i = 0; i < nargs; i++) { if (upeek(pid, REG_A0 + i, &tcp->u_arg[i]) < 0) return -1; } } } #elif defined (POWERPC) #ifndef PT_ORIG_R3 #define PT_ORIG_R3 34 #endif { int i; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) { if (upeek(pid, (i==0) ? (sizeof(unsigned long)*PT_ORIG_R3) : ((i+PT_R3)*sizeof(unsigned long)), &tcp->u_arg[i]) < 0) return -1; } } #elif defined (SPARC) || defined (SPARC64) { int i; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) tcp->u_arg[i] = *((&regs.r_o0) + i); } #elif defined (HPPA) { int i; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) { if (upeek(pid, PT_GR26-4*i, &tcp->u_arg[i]) < 0) return -1; } } #elif defined(ARM) { int i; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) tcp->u_arg[i] = regs.uregs[i]; } #elif defined(SH) { int i; static int syscall_regs[] = { REG_REG0+4, REG_REG0+5, REG_REG0+6, REG_REG0+7, REG_REG0, REG_REG0+1, REG_REG0+2 }; tcp->u_nargs = sysent[tcp->scno].nargs; for (i = 0; i < tcp->u_nargs; i++) { if (upeek(pid, 4*syscall_regs[i], &tcp->u_arg[i]) < 0) return -1; } } #elif defined(SH64) { int i; /* Registers used by SH5 Linux system calls for parameters */ static int syscall_regs[] = { 2, 3, 4, 5, 6, 7 }; /* * TODO: should also check that the number of arguments encoded * in the trap number matches the number strace expects. */ /* assert(sysent[tcp->scno].nargs < sizeof(syscall_regs)/sizeof(syscall_regs[0])); */ tcp->u_nargs = sysent[tcp->scno].nargs; for (i = 0; i < tcp->u_nargs; i++) { if (upeek(pid, REG_GENERAL(syscall_regs[i]), &tcp->u_arg[i]) < 0) return -1; } } #elif defined(X86_64) { int i; static int argreg[SUPPORTED_PERSONALITIES][MAX_ARGS] = { {RDI,RSI,RDX,R10,R8,R9}, /* x86-64 ABI */ {RBX,RCX,RDX,RSI,RDI,RBP} /* i386 ABI */ }; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) { if (upeek(pid, argreg[current_personality][i]*8, &tcp->u_arg[i]) < 0) return -1; } } #else /* Other architecture (like i386) (32bits specific) */ { int i; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) { if (upeek(pid, i*4, &tcp->u_arg[i]) < 0) return -1; } } #endif #endif /* LINUX */ #ifdef SUNOS4 { int i; if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = MAX_ARGS; for (i = 0; i < tcp->u_nargs; i++) { struct user *u; if (upeek(pid, uoff(u_arg[0]) + (i*sizeof(u->u_arg[0])), &tcp->u_arg[i]) < 0) return -1; } } #endif /* SUNOS4 */ #ifdef SVR4 #ifdef MIPS /* * SGI is broken: even though it has pr_sysarg, it doesn't * set them on system call entry. Get a clue. */ if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = tcp->status.pr_nsysarg; if (tcp->u_nargs > 4) { memcpy(tcp->u_arg, &tcp->status.pr_reg[CTX_A0], 4*sizeof(tcp->u_arg[0])); umoven(tcp, tcp->status.pr_reg[CTX_SP] + 16, (tcp->u_nargs - 4)*sizeof(tcp->u_arg[0]), (char *) (tcp->u_arg + 4)); } else { memcpy(tcp->u_arg, &tcp->status.pr_reg[CTX_A0], tcp->u_nargs*sizeof(tcp->u_arg[0])); } #elif UNIXWARE >= 2 /* * Like SGI, UnixWare doesn't set pr_sysarg until system call exit */ if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = tcp->status.pr_lwp.pr_nsysarg; umoven(tcp, tcp->status.PR_REG[UESP] + 4, tcp->u_nargs*sizeof(tcp->u_arg[0]), (char *) tcp->u_arg); #elif defined (HAVE_PR_SYSCALL) if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = tcp->status.pr_nsysarg; { int i; for (i = 0; i < tcp->u_nargs; i++) tcp->u_arg[i] = tcp->status.pr_sysarg[i]; } #elif defined (I386) if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs != -1) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = 5; umoven(tcp, tcp->status.PR_REG[UESP] + 4, tcp->u_nargs*sizeof(tcp->u_arg[0]), (char *) tcp->u_arg); #else I DONT KNOW WHAT TO DO #endif /* !HAVE_PR_SYSCALL */ #endif /* SVR4 */ #ifdef FREEBSD if (tcp->scno >= 0 && tcp->scno < nsyscalls && sysent[tcp->scno].nargs > tcp->status.val) tcp->u_nargs = sysent[tcp->scno].nargs; else tcp->u_nargs = tcp->status.val; if (tcp->u_nargs < 0) tcp->u_nargs = 0; if (tcp->u_nargs > MAX_ARGS) tcp->u_nargs = MAX_ARGS; switch(regs.r_eax) { case SYS___syscall: pread(tcp->pfd, &tcp->u_arg, tcp->u_nargs * sizeof(unsigned long), regs.r_esp + sizeof(int) + sizeof(quad_t)); break; case SYS_syscall: pread(tcp->pfd, &tcp->u_arg, tcp->u_nargs * sizeof(unsigned long), regs.r_esp + 2 * sizeof(int)); break; default: pread(tcp->pfd, &tcp->u_arg, tcp->u_nargs * sizeof(unsigned long), regs.r_esp + sizeof(int)); break; } #endif /* FREEBSD */ return 1; } int trace_syscall(tcp) struct tcb *tcp; { int sys_res; struct timeval tv; int res; /* Measure the exit time as early as possible to avoid errors. */ if (dtime && (tcp->flags & TCB_INSYSCALL)) gettimeofday(&tv, NULL); res = get_scno(tcp); if (res != 1) return res; res = syscall_fixup(tcp); if (res != 1) return res; if (tcp->flags & TCB_INSYSCALL) { long u_error; res = get_error(tcp); if (res != 1) return res; internal_syscall(tcp); if (tcp->scno >= 0 && tcp->scno < nsyscalls && !(qual_flags[tcp->scno] & QUAL_TRACE)) { tcp->flags &= ~TCB_INSYSCALL; return 0; } if (tcp->flags & TCB_REPRINT) { printleader(tcp); tprintf("<... "); if (tcp->scno >= nsyscalls || tcp->scno < 0) tprintf("syscall_%lu", tcp->scno); else tprintf("%s", sysent[tcp->scno].sys_name); tprintf(" resumed> "); } if (cflag && tcp->scno < nsyscalls && tcp->scno >= 0) { if (counts == NULL) { counts = calloc(sizeof *counts, nsyscalls); if (counts == NULL) { fprintf(stderr, "\ strace: out of memory for call counts\n"); exit(1); } } counts[tcp->scno].calls++; if (tcp->u_error) counts[tcp->scno].errors++; tv_sub(&tv, &tv, &tcp->etime); #ifndef HAVE_ANDROID_OS #ifdef LINUX if (tv_cmp(&tv, &tcp->dtime) > 0) { static struct timeval one_tick; if (one_tick.tv_usec == 0) { /* Initialize it. */ struct itimerval it; memset(&it, 0, sizeof it); it.it_interval.tv_usec = 1; setitimer(ITIMER_REAL, &it, NULL); getitimer(ITIMER_REAL, &it); one_tick = it.it_interval; } if (tv_nz(&tcp->dtime)) tv = tcp->dtime; else if (tv_cmp(&tv, &one_tick) > 0) { if (tv_cmp(&shortest, &one_tick) < 0) tv = shortest; else tv = one_tick; } } #endif /* LINUX */ #endif if (tv_cmp(&tv, &shortest) < 0) shortest = tv; tv_add(&counts[tcp->scno].time, &counts[tcp->scno].time, &tv); tcp->flags &= ~TCB_INSYSCALL; return 0; } if (tcp->scno >= nsyscalls || tcp->scno < 0 || (qual_flags[tcp->scno] & QUAL_RAW)) sys_res = printargs(tcp); else { if (not_failing_only && tcp->u_error) return 0; /* ignore failed syscalls */ sys_res = (*sysent[tcp->scno].sys_func)(tcp); } u_error = tcp->u_error; tprintf(") "); tabto(acolumn); if (tcp->scno >= nsyscalls || tcp->scno < 0 || qual_flags[tcp->scno] & QUAL_RAW) { if (u_error) tprintf("= -1 (errno %ld)", u_error); else tprintf("= %#lx", tcp->u_rval); } else if (!(sys_res & RVAL_NONE) && u_error) { switch (u_error) { #ifdef LINUX case ERESTARTSYS: tprintf("= ? ERESTARTSYS (To be restarted)"); break; case ERESTARTNOINTR: tprintf("= ? ERESTARTNOINTR (To be restarted)"); break; case ERESTARTNOHAND: tprintf("= ? ERESTARTNOHAND (To be restarted)"); break; case ERESTART_RESTARTBLOCK: tprintf("= ? ERESTART_RESTARTBLOCK (To be restarted)"); break; #endif /* LINUX */ default: tprintf("= -1 "); if (u_error < 0) tprintf("E??? (errno %ld)", u_error); else if (u_error < nerrnos) tprintf("%s (%s)", errnoent[u_error], strerror(u_error)); else tprintf("ERRNO_%ld (%s)", u_error, strerror(u_error)); break; } } else { if (sys_res & RVAL_NONE) tprintf("= ?"); else { switch (sys_res & RVAL_MASK) { case RVAL_HEX: tprintf("= %#lx", tcp->u_rval); break; case RVAL_OCTAL: tprintf("= %#lo", tcp->u_rval); break; case RVAL_UDECIMAL: tprintf("= %lu", tcp->u_rval); break; case RVAL_DECIMAL: tprintf("= %ld", tcp->u_rval); break; #ifdef HAVE_LONG_LONG case RVAL_LHEX: tprintf("= %#llx", tcp->u_lrval); break; case RVAL_LOCTAL: tprintf("= %#llo", tcp->u_lrval); break; case RVAL_LUDECIMAL: tprintf("= %llu", tcp->u_lrval); break; case RVAL_LDECIMAL: tprintf("= %lld", tcp->u_lrval); break; #endif default: fprintf(stderr, "invalid rval format\n"); break; } } if ((sys_res & RVAL_STR) && tcp->auxstr) tprintf(" (%s)", tcp->auxstr); } if (dtime) { tv_sub(&tv, &tv, &tcp->etime); tprintf(" <%ld.%06ld>", (long) tv.tv_sec, (long) tv.tv_usec); } printtrailer(tcp); dumpio(tcp); if (fflush(tcp->outf) == EOF) return -1; tcp->flags &= ~TCB_INSYSCALL; return 0; } /* Entering system call */ res = syscall_enter(tcp); if (res != 1) return res; switch (known_scno(tcp)) { #ifdef LINUX #if !defined (ALPHA) && !defined(SPARC) && !defined(SPARC64) && !defined(MIPS) && !defined(HPPA) && !defined(__ARM_EABI__) //ANDROID case SYS_socketcall: decode_subcall(tcp, SYS_socket_subcall, SYS_socket_nsubcalls, deref_style); break; case SYS_ipc: decode_subcall(tcp, SYS_ipc_subcall, SYS_ipc_nsubcalls, shift_style); break; #endif /* !ALPHA && !MIPS && !SPARC && !SPARC64 && !HPPA */ #if defined (SPARC) || defined (SPARC64) case SYS_socketcall: sparc_socket_decode (tcp); break; #endif #endif /* LINUX */ #ifdef SVR4 #ifdef SYS_pgrpsys_subcall case SYS_pgrpsys: decode_subcall(tcp, SYS_pgrpsys_subcall, SYS_pgrpsys_nsubcalls, shift_style); break; #endif /* SYS_pgrpsys_subcall */ #ifdef SYS_sigcall_subcall case SYS_sigcall: decode_subcall(tcp, SYS_sigcall_subcall, SYS_sigcall_nsubcalls, mask_style); break; #endif /* SYS_sigcall_subcall */ case SYS_msgsys: decode_subcall(tcp, SYS_msgsys_subcall, SYS_msgsys_nsubcalls, shift_style); break; case SYS_shmsys: decode_subcall(tcp, SYS_shmsys_subcall, SYS_shmsys_nsubcalls, shift_style); break; case SYS_semsys: decode_subcall(tcp, SYS_semsys_subcall, SYS_semsys_nsubcalls, shift_style); break; #if 0 /* broken */ case SYS_utssys: decode_subcall(tcp, SYS_utssys_subcall, SYS_utssys_nsubcalls, shift_style); break; #endif case SYS_sysfs: decode_subcall(tcp, SYS_sysfs_subcall, SYS_sysfs_nsubcalls, shift_style); break; case SYS_spcall: decode_subcall(tcp, SYS_spcall_subcall, SYS_spcall_nsubcalls, shift_style); break; #ifdef SYS_context_subcall case SYS_context: decode_subcall(tcp, SYS_context_subcall, SYS_context_nsubcalls, shift_style); break; #endif /* SYS_context_subcall */ #ifdef SYS_door_subcall case SYS_door: decode_subcall(tcp, SYS_door_subcall, SYS_door_nsubcalls, door_style); break; #endif /* SYS_door_subcall */ #ifdef SYS_kaio_subcall case SYS_kaio: decode_subcall(tcp, SYS_kaio_subcall, SYS_kaio_nsubcalls, shift_style); break; #endif #endif /* SVR4 */ #ifdef FREEBSD case SYS_msgsys: case SYS_shmsys: case SYS_semsys: decode_subcall(tcp, 0, 0, table_style); break; #endif #ifdef SUNOS4 case SYS_semsys: decode_subcall(tcp, SYS_semsys_subcall, SYS_semsys_nsubcalls, shift_style); break; case SYS_msgsys: decode_subcall(tcp, SYS_msgsys_subcall, SYS_msgsys_nsubcalls, shift_style); break; case SYS_shmsys: decode_subcall(tcp, SYS_shmsys_subcall, SYS_shmsys_nsubcalls, shift_style); break; #endif } internal_syscall(tcp); if (tcp->scno >=0 && tcp->scno < nsyscalls && !(qual_flags[tcp->scno] & QUAL_TRACE)) { tcp->flags |= TCB_INSYSCALL; return 0; } if (cflag) { gettimeofday(&tcp->etime, NULL); tcp->flags |= TCB_INSYSCALL; return 0; } printleader(tcp); tcp->flags &= ~TCB_REPRINT; tcp_last = tcp; if (tcp->scno >= nsyscalls || tcp->scno < 0) tprintf("syscall_%lu(", tcp->scno); else tprintf("%s(", sysent[tcp->scno].sys_name); if (tcp->scno >= nsyscalls || tcp->scno < 0 || ((qual_flags[tcp->scno] & QUAL_RAW) && tcp->scno != SYS_exit)) sys_res = printargs(tcp); else sys_res = (*sysent[tcp->scno].sys_func)(tcp); if (fflush(tcp->outf) == EOF) return -1; tcp->flags |= TCB_INSYSCALL; /* Measure the entrance time as late as possible to avoid errors. */ if (dtime) gettimeofday(&tcp->etime, NULL); return sys_res; } int printargs(tcp) struct tcb *tcp; { if (entering(tcp)) { int i; for (i = 0; i < tcp->u_nargs; i++) tprintf("%s%#lx", i ? ", " : "", tcp->u_arg[i]); } return 0; } long getrval2(tcp) struct tcb *tcp; { long val = -1; #ifdef LINUX #if defined (SPARC) || defined (SPARC64) struct regs regs; if (ptrace(PTRACE_GETREGS,tcp->pid,(char *)&regs,0) < 0) return -1; val = regs.r_o1; #elif defined(SH) if (upeek(tcp->pid, 4*(REG_REG0+1), &val) < 0) return -1; #elif defined(IA64) if (upeek(tcp->pid, PT_R9, &val) < 0) return -1; #endif /* SPARC || SPARC64 */ #endif /* LINUX */ #ifdef SUNOS4 if (upeek(tcp->pid, uoff(u_rval2), &val) < 0) return -1; #endif /* SUNOS4 */ #ifdef SVR4 #ifdef SPARC val = tcp->status.PR_REG[R_O1]; #endif /* SPARC */ #ifdef I386 val = tcp->status.PR_REG[EDX]; #endif /* I386 */ #ifdef X86_64 val = tcp->status.PR_REG[RDX]; #endif /* X86_64 */ #ifdef MIPS val = tcp->status.PR_REG[CTX_V1]; #endif /* MIPS */ #endif /* SVR4 */ #ifdef FREEBSD struct reg regs; pread(tcp->pfd_reg, &regs, sizeof(regs), 0); val = regs.r_edx; #endif return val; } /* * Apparently, indirect system calls have already be converted by ptrace(2), * so if you see "indir" this program has gone astray. */ int sys_indir(tcp) struct tcb *tcp; { int i, scno, nargs; if (entering(tcp)) { if ((scno = tcp->u_arg[0]) > nsyscalls) { fprintf(stderr, "Bogus syscall: %u\n", scno); return 0; } nargs = sysent[scno].nargs; tprintf("%s", sysent[scno].sys_name); for (i = 0; i < nargs; i++) tprintf(", %#lx", tcp->u_arg[i+1]); } return 0; } static int time_cmp(a, b) void *a; void *b; { return -tv_cmp(&counts[*((int *) a)].time, &counts[*((int *) b)].time); } static int syscall_cmp(a, b) void *a; void *b; { return strcmp(sysent[*((int *) a)].sys_name, sysent[*((int *) b)].sys_name); } static int count_cmp(a, b) void *a; void *b; { int m = counts[*((int *) a)].calls, n = counts[*((int *) b)].calls; return (m < n) ? 1 : (m > n) ? -1 : 0; } static int (*sortfun)(); static struct timeval overhead = { -1, -1 }; void set_sortby(sortby) char *sortby; { if (strcmp(sortby, "time") == 0) sortfun = time_cmp; else if (strcmp(sortby, "calls") == 0) sortfun = count_cmp; else if (strcmp(sortby, "name") == 0) sortfun = syscall_cmp; else if (strcmp(sortby, "nothing") == 0) sortfun = NULL; else { fprintf(stderr, "invalid sortby: `%s'\n", sortby); exit(1); } } void set_overhead(n) int n; { overhead.tv_sec = n / 1000000; overhead.tv_usec = n % 1000000; } void call_summary(outf) FILE *outf; { int i, j; int call_cum, error_cum; struct timeval tv_cum, dtv; double percent; char *dashes = "-------------------------"; char error_str[16]; int *sorted_count = malloc(nsyscalls * sizeof(int)); call_cum = error_cum = tv_cum.tv_sec = tv_cum.tv_usec = 0; if (overhead.tv_sec == -1) { tv_mul(&overhead, &shortest, 8); tv_div(&overhead, &overhead, 10); } for (i = 0; i < nsyscalls; i++) { sorted_count[i] = i; if (counts == NULL || counts[i].calls == 0) continue; tv_mul(&dtv, &overhead, counts[i].calls); tv_sub(&counts[i].time, &counts[i].time, &dtv); call_cum += counts[i].calls; error_cum += counts[i].errors; tv_add(&tv_cum, &tv_cum, &counts[i].time); } if (counts && sortfun) qsort((void *) sorted_count, nsyscalls, sizeof(int), sortfun); fprintf(outf, "%6.6s %11.11s %11.11s %9.9s %9.9s %s\n", "% time", "seconds", "usecs/call", "calls", "errors", "syscall"); fprintf(outf, "%6.6s %11.11s %11.11s %9.9s %9.9s %-16.16s\n", dashes, dashes, dashes, dashes, dashes, dashes); if (counts) { for (i = 0; i < nsyscalls; i++) { j = sorted_count[i]; if (counts[j].calls == 0) continue; tv_div(&dtv, &counts[j].time, counts[j].calls); if (counts[j].errors) sprintf(error_str, "%d", counts[j].errors); else error_str[0] = '\0'; percent = (100.0 * tv_float(&counts[j].time) / tv_float(&tv_cum)); fprintf(outf, "%6.2f %4ld.%06ld %11ld %9d %9.9s %s\n", percent, (long) counts[j].time.tv_sec, (long) counts[j].time.tv_usec, (long) 1000000 * dtv.tv_sec + dtv.tv_usec, counts[j].calls, error_str, sysent[j].sys_name); } } free(sorted_count); fprintf(outf, "%6.6s %11.11s %11.11s %9.9s %9.9s %-16.16s\n", dashes, dashes, dashes, dashes, dashes, dashes); if (error_cum) sprintf(error_str, "%d", error_cum); else error_str[0] = '\0'; fprintf(outf, "%6.6s %4ld.%06ld %11.11s %9d %9.9s %s\n", "100.00", (long) tv_cum.tv_sec, (long) tv_cum.tv_usec, "", call_cum, error_str, "total"); }
gaoyuexit/-QQ-
QQ_FriendsList_Demo/QQ_FriendsList_Demo/GYFriend.h
<filename>QQ_FriendsList_Demo/QQ_FriendsList_Demo/GYFriend.h // // GYFriend.h // QQ_FriendsList_Demo // // Created by 郜宇 on 15/11/3. // Copyright © 2015年 郜宇. All rights reserved. // #import <Foundation/Foundation.h> @interface GYFriend : NSObject // 头像 @property (nonatomic,copy)NSString *icon; // 昵称 @property (nonatomic,copy)NSString *name; // 个性签名 @property (nonatomic,copy)NSString *intro; // 是否是vip @property (nonatomic,assign,getter = isVip)BOOL vip; - (instancetype)initWithDict:(NSDictionary *)dict; + (instancetype)friendWithDict:(NSDictionary *)dict; @end
gaoyuexit/-QQ-
QQ_FriendsList_Demo/QQ_FriendsList_Demo/GYGroup.h
<gh_stars>0 // // GYGroup.h // QQ_FriendsList_Demo // // Created by 郜宇 on 15/11/3. // Copyright © 2015年 郜宇. All rights reserved. // #import <Foundation/Foundation.h> @interface GYGroup : NSObject // 组名 @property (nonatomic,copy)NSString *name; // 在线人数 @property (nonatomic,assign)int online; // 当前组中的所有好友数据 @property (nonatomic,strong)NSArray *friends; // 是否可见 @property (nonatomic,assign,getter = isVisible)BOOL Visible; - (instancetype)initWithDict:(NSDictionary *)dict; + (instancetype)groupWithDict:(NSDictionary *)dict; @end
gaoyuexit/-QQ-
QQ_FriendsList_Demo/QQ_FriendsList_Demo/GYGroupHeaderView.h
// // GYGroupHeaderView.h // QQ_FriendsList_Demo // // Created by 郜宇 on 15/11/3. // Copyright © 2015年 郜宇. All rights reserved. // #import <UIKit/UIKit.h> @class GYGroup; @class GYGroupHeaderView; @protocol GYGroupHeaderViewDelelgate <NSObject> @optional - (void)groupHeaderViewDidClick:(GYGroupHeaderView *)groupHeaderView; @end @interface GYGroupHeaderView : UITableViewHeaderFooterView @property (nonatomic,strong)GYGroup *group; //控件的代理用weak @property (nonatomic,weak)id<GYGroupHeaderViewDelelgate>delegate; + (instancetype)headerViewWithTableView:(UITableView *)tableView; @end
gaoyuexit/-QQ-
QQ_FriendsList_Demo/QQ_FriendsList_Demo/QQFriendsListController.h
// // QQFriendsListController.h // QQ_FriendsList_Demo // // Created by 郜宇 on 15/11/3. // Copyright © 2015年 郜宇. All rights reserved. // #import <UIKit/UIKit.h> @interface QQFriendsListController : UITableViewController @end
gaoyuexit/-QQ-
QQ_FriendsList_Demo/QQ_FriendsList_Demo/GYFriendCell.h
<filename>QQ_FriendsList_Demo/QQ_FriendsList_Demo/GYFriendCell.h // // GYFriendCell.h // QQ_FriendsList_Demo // // Created by 郜宇 on 15/11/3. // Copyright © 2015年 郜宇. All rights reserved. // #import <UIKit/UIKit.h> @class GYFriend; @interface GYFriendCell : UITableViewCell @property (nonatomic,strong)GYFriend *friends; + (instancetype)cellWithTableView:(UITableView *)tableView; @end
lh2/mpv-subserv
main.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "client.h" extern void Start(char *title); extern void PosChanged(double pos); extern void SubDelayChanged(double delay); extern void Stop(); static int handle_file_load(mpv_handle *handle) { char *media_title; int err; err = mpv_get_property(handle, "media-title", MPV_FORMAT_STRING, &media_title); if (err != 0) { if (!(media_title = malloc(50))) { return 1; } snprintf(media_title, 49, "error getting title %d", err); } Start(media_title); return 0; } static void handle_prop_event(mpv_handle *handle, int reply_userdata, mpv_event_property *event_prop) { if (event_prop->data == NULL) { return; } switch (reply_userdata) { case 1: PosChanged(*(double *)(event_prop->data)); break; case 2: SubDelayChanged(*(double *)(event_prop->data)); break; } } int mpv_open_cplugin(mpv_handle *handle) { char *enabled; mpv_event *event; int err; enabled = getenv("MPV_SUBSERV"); if (enabled == NULL || strcmp(enabled, "1") != 0) { printf("mpv-subserv disabled"); return 0; } err = mpv_observe_property(handle, 1, "time-pos", MPV_FORMAT_DOUBLE); if (err != 0) { return err; } err = mpv_observe_property(handle, 2, "sub-delay", MPV_FORMAT_DOUBLE); if (err != 0) { return err; } while (1) { event = mpv_wait_event(handle, -1); if (event->event_id == MPV_EVENT_SHUTDOWN) { break; } switch (event->event_id) { case MPV_EVENT_FILE_LOADED: if ((err = handle_file_load(handle)) != 0) { return err; } break; case MPV_EVENT_PROPERTY_CHANGE: handle_prop_event(handle, event->reply_userdata, (mpv_event_property *)event->data); break; } } Stop(); return 0; }
zSoNz/GNImageProgressBar
GNImageProgressBar/GNImageProgressBar.h
// // GNImageProgressBar.h // GNImageProgressBar // // Created by george on 03/03/2020. // Copyright © 2020 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for GNImageProgressBar. FOUNDATION_EXPORT double GNImageProgressBarVersionNumber; //! Project version string for GNImageProgressBar. FOUNDATION_EXPORT const unsigned char GNImageProgressBarVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <GNImageProgressBar/PublicHeader.h>
Achierius/aolc
include/internal/aolc/compare_buffer_functions.h
#ifndef __AOLC_COMPARE_BUFFER_FUNCTIONS_H #define __AOLC_COMPARE_BUFFER_FUNCTIONS_H #include "gtest/gtest.h" #include <stdio.h> #include <cstring> #include <mutex> #include <iostream> #include "aolc/_test_string.h" #include <functional> /* * Class 0: (int) * => strerror * >char* * * Class 1: (char*) * => strlen * >size_t * * Class 2: (char*, char*) * => strcat strcpy strpbrk strstr strtok strspn strcspn * > * * Class 3: (char*, char*, size_t) * => strncmp strncpy strxfrm memcpy memmove memcmp strncat * * Class 4: (char*, int) * => strchr strrchr strcmp strcoll * * Class 5: (char*, int, size_t) * => memchr memset */ using VoidBuffFn = std::function<void* ( void*, const void*)>; using ConstVoidBuffFn = std::function<void* (const void*, const void*)>; using SingleVoidBuffFn = std::function<void* ( void* )>; using ConstSingleVoidBuffFn = std::function<void* (const void* )>; using CharBuffFn = std::function<char* ( char*, const char*)>; using ConstCharBuffFn = std::function<char* (const char*, const char*)>; using SingleCharBuffFn = std::function<char* ( char* )>; using ConstSingleCharBuffFn = std::function<char* (const char* )>; enum class EqualityMode { kStrictEquality, kBufferRelativeEquality, kSignEquality, }; const size_t kMaxBufferSize = 4096; const char kCanaryByte = 0xCA; const size_t kCanaryLengthBytes = 4; template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } //using Class2Fn = std::function<char* (char*, const char*, size_t n)>; /* I did these all manually (rather than using templates) because I wasn't * confident I could use enable_if properly so as to avoid accidentally * violating the standard -- lots of tricky aliasing going on in these */ template<typename RetT> void CompareBufferFuncEval(std::function<RetT (void*, const void*)> test_func, std::function<RetT (void*, const void*)> true_func, const void* s1, const void* s2, size_t l1, size_t l2, EqualityMode equality_mode) { std::mutex buffers_lock; char* canary_lock = (char*) calloc(1, kCanaryLengthBytes); char* buffer_src1 = (char*) calloc(1, kMaxBufferSize); char* canary_src1 = (char*) calloc(1, kCanaryLengthBytes); char* buffer_src2 = (char*) calloc(1, kMaxBufferSize); char* canary_src2 = (char*) calloc(1, kCanaryLengthBytes); char* buffer_dst1 = (char*) calloc(1, kMaxBufferSize); char* canary_dst1 = (char*) calloc(1, kCanaryLengthBytes); char* buffer_dst2 = (char*) calloc(1, kMaxBufferSize); char* canary_dst2 = (char*) calloc(1, kCanaryLengthBytes); ASSERT_LT(l1, kMaxBufferSize); ASSERT_LT(l2, kMaxBufferSize); auto CheckCanary = [&](char* canary) { for (int i = 0; i < kCanaryLengthBytes; i++) { ASSERT_EQ(canary[i], kCanaryByte); } }; auto CheckCanaries = [&]() { CheckCanary(canary_lock); CheckCanary(canary_src1); CheckCanary(canary_src2); CheckCanary(canary_dst1); CheckCanary(canary_dst2); }; auto CleanBuffers = [&]() { memset(buffer_src1, '\0', kMaxBufferSize); memset(buffer_src2, '\0', kMaxBufferSize); memset(buffer_dst1, '\0', kMaxBufferSize); memset(buffer_dst2, '\0', kMaxBufferSize); memset(canary_lock, kCanaryByte, kCanaryLengthBytes); memset(canary_src2, kCanaryByte, kCanaryLengthBytes); memset(canary_src1, kCanaryByte, kCanaryLengthBytes); memset(canary_dst1, kCanaryByte, kCanaryLengthBytes); memset(canary_dst2, kCanaryByte, kCanaryLengthBytes); }; /* Prepare to access global buffers */ buffers_lock.lock(); CleanBuffers(); /* Copy given arguments into global buffers; we now have identical * duplicate buffers to pass as arguments to each function, so as * to properly compare their functionality. */ memmove(buffer_dst1, s1, l1); memmove(buffer_dst2, s1, l1); memmove(buffer_src1, s2, l2); memmove(buffer_src2, s2, l2); /* Alias buffer names for clarity */ void* true_s1 = buffer_dst1; void* test_s1 = buffer_dst2; void* true_s2 = buffer_src1; void* test_s2 = buffer_src2; /* Evaluate each of the given functions and store their return values for * later comparison */ RetT true_retval = true_func(true_s1, true_s2); RetT test_retval = test_func(test_s1, test_s2); /* Check to see if any stack canary has been overwritten -- this would * indicate a buffer overflow. Assuming we're not dealing with hostile code * -- libc <string.h> functions are by no means meant to be safe in this * regard -- this will catch all buffer overruns which write * 'continuously', that is without skipping large segments of memory as * they run out of bounds. */ CheckCanaries(); /* Now we compare the contents of both sets of buffers: the behavior of both * given functions is expected to be identical on each. */ EXPECT_EQ(memcmp(test_s1, true_s1, kMaxBufferSize), 0); EXPECT_EQ(memcmp(test_s2, true_s2, kMaxBufferSize), 0); switch (equality_mode) { case EqualityMode::kStrictEquality: EXPECT_EQ(test_retval, true_retval); break; case EqualityMode::kBufferRelativeEquality: /* In general, these functions return either their *dst argument or a * pointer to a location within it -- as such, as long as neither function * errors out (by returning nullptr) we don't compare the actual return * values of each function, but rather the offset of their return values * from their *dst argument. */ if (true_retval == static_cast<RetT>(0) || test_retval == static_cast<RetT>(0)) { EXPECT_EQ(test_retval, static_cast<RetT>(0)); EXPECT_EQ(test_retval, true_retval); } else { EXPECT_EQ((intptr_t) true_retval - (intptr_t) true_s1, (intptr_t) test_retval - (intptr_t) test_s1); } break; case EqualityMode::kSignEquality: /* These functions (strcmp, memcmp) return an integer value, in which * the result of their computation is embedded via the sign -- positive * denoting arg2 > arg1, negative denoting arg2 < arg1, and 0 denoting * arg1 == arg2; beyond this, the value is not specified. */ EXPECT_EQ(sgn<RetT>(true_retval), sgn<RetT>(test_retval)); break; } /* Release global buffers */ buffers_lock.unlock(); } template<typename RetT, typename ArgT1, typename ArgT2> void CompareBufferFunctions(std::function<RetT (ArgT1, ArgT2)> test_func, std::function<RetT (ArgT1, ArgT2)> true_func, const void* buff_1, const void* buff_2, size_t l1, size_t l2, EqualityMode equality_mode = EqualityMode::kBufferRelativeEquality) { auto test_func_wrapper = [=](void* s1, const void* s2) { ArgT1 arg1 = static_cast<ArgT1>(s1); ArgT2 arg2 = static_cast<ArgT2>(s2); return static_cast<RetT>(test_func(arg1, arg2)); }; auto true_func_wrapper = [=](void* s1, const void* s2) { ArgT1 arg1 = static_cast<ArgT1>(s1); ArgT2 arg2 = static_cast<ArgT2>(s2); return static_cast<RetT>(true_func(arg1, arg2)); }; CompareBufferFuncEval<RetT>(test_func_wrapper, true_func_wrapper, buff_1, buff_2, l1, l2, equality_mode); } template<typename RetT, typename ArgT1, typename ArgT2> void CompareBufferFunctions(std::function<RetT (ArgT1, ArgT2)> test_func, std::function<RetT (ArgT1, ArgT2)> true_func, const void* buff_1, const void* buff_2, EqualityMode equality_mode = EqualityMode::kBufferRelativeEquality) { CompareBufferFunctions<RetT, ArgT1, ArgT2>( test_func, true_func, buff_1, buff_2, strlen(static_cast<const char*>(buff_1)), strlen(static_cast<const char*>(buff_2)), equality_mode); } template<typename RetT, typename ArgT1> void CompareBufferFunctions(std::function<RetT (ArgT1)> test_func, std::function<RetT (ArgT1)> true_func, const void* buff_1, size_t l1, EqualityMode equality_mode = EqualityMode::kBufferRelativeEquality) { auto test_func_wrapper = [=](ArgT1 s1, const void* s2) { return test_func(s1); }; auto true_func_wrapper = [=](ArgT1 s1, const void* s2) { return true_func(s1); }; CompareBufferFunctions<RetT, ArgT1, const void*>( test_func_wrapper, true_func_wrapper, buff_1, nullptr, l1, 0, equality_mode); } #endif//__AOLC_COMPARE_BUFFER_FUNCTIONS_H
Achierius/aolc
src/c/sys_libc_standin.c
<reponame>Achierius/aolc<filename>src/c/sys_libc_standin.c #include <aolc/_test_string.h> #include <string.h> void *_memcpy(void *dest, const void *src, size_t n) { return memcpy(dest, src, n); } void *_memmove(void *dest, const void *src, size_t n) { return memmove(dest, src, n); } void *_memchr(const void *str, int c, size_t n) { return memchr(str, c, n); } int _memcmp(const void *str1, const void *str2, size_t n) { return memcmp(str1, str2, n); } void *_memset(void *str, int c, size_t n) { return memset(str, c, n); } char *_strcat(char *dest, const char *src) { return strcat(dest, src); } char *_strncat(char *dest, const char *src, size_t n) { return strncat(dest, src, n); } char *_strchr(const char *str, int c) { return strchr(str, c); } char *_strrchr(const char *str, int c) { return strrchr(str, c); } int _strcmp(const char *str1, const char *str2) { return strcmp(str1, str2); } int _strncmp(const char *str1, const char *str2, size_t n) { return strncmp(str1, str2, n); } int _strcoll(const char *str1, const char *str2) { return strcoll(str1, str2); } char *_strcpy(char *dest, const char *src) { return strcpy(dest, src); } char *_strncpy(char *dest, const char *src, size_t n) { return strncpy(dest, src, n); } char *_strerror(int errnum) { return strerror(errnum); } size_t _strspn(const char *str1, const char *accept) { return strspn(str1, accept); } size_t _strcspn(const char *str1, const char *reject) { return strcspn(str1, reject); } size_t _strlen(const char *str) { return strlen(str); } char *_strpbrk(const char *str1, const char *str2) { return strpbrk(str1, str2); } char *_strstr(const char *haystack, const char *needle) { return strstr(haystack, needle); } char *_strtok(char *str, const char *delim) { return strtok(str, delim); } size_t _strxfrm(char *dest, const char *src, size_t n) { return strxfrm(dest, src, n); }
Letractively/simplesitemapcreator
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMessageBox> #include <QClipboard> #include <QFileDialog> #include <QTextStream> #include <QList> #include <QStringList> #include <libxml2/libxml/HTMLparser.h> #include <curl/curl.h> #include <cstring> #include "xmlhighlighter.h" #include <QDebug> struct linkItem { QString title; QString link; QString referrer; QString modtime; bool parsed; }; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_btnGo_clicked(); void on_btnCopy_clicked(); void on_btnClear_clicked(); void on_btnSave_clicked(); void on_btnAbout_clicked(); private: Ui::MainWindow *ui; XmlHighlighter *highlighter; int linkCount; QList<linkItem> links; QStringList linkList; void getlinks(xmlNode *a_node); void addLink(char *link, char *title, char *ref, char *header); }; #endif // MAINWINDOW_H
Letractively/simplesitemapcreator
xmlhighlighter.h
<gh_stars>0 /* $URL$ $Rev$ $Author$ $Date$ $Id$ */ /* ** Copyright 2009-10 <NAME>, <NAME> and the ** University of Victoria Humanities Computing and Media ** Centre. ** This file is part of the projXMLEditor project which in ** turn belongs to the Image Markup Tool version 2.0 ** project. The purpose of svgIconsTest is to provide a ** platform to test and learn various features of Qt, and ** to provide a semi-useful tool to aid in the rapid ** creation and editing of resource files containing SVG ** icons for Qt application development. ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** You may also use this code under the Mozilla Public Licence ** version 1.1. MPL 1.1 can be found at http://www.mozilla.org/MPL/MPL-1.1.html. ** "svgIconsTest" is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. */ #ifndef XMLHIGHLIGHTER_H #define XMLHIGHLIGHTER_H #include <QSyntaxHighlighter> #include <QHash> #include <QTextCharFormat> QT_BEGIN_NAMESPACE class QTextDocument; QT_END_NAMESPACE class XmlHighlighter : public QSyntaxHighlighter { Q_OBJECT public: XmlHighlighter(QTextDocument *parent = 0); protected: void highlightBlock(const QString &text); void highlightSubBlock(const QString &text, const int startIndex, const int currState); private: struct HighlightingRule { QRegExp pattern; QTextCharFormat format; }; QVector<HighlightingRule> hlRules; QRegExp xmlProcInstStartExpression; QRegExp xmlProcInstEndExpression; QRegExp xmlCommentStartExpression; QRegExp xmlCommentEndExpression; QRegExp xmlDoctypeStartExpression; QRegExp xmlDoctypeEndExpression; QRegExp xmlOpenTagStartExpression; QRegExp xmlOpenTagEndExpression; QRegExp xmlCloseTagStartExpression; QRegExp xmlCloseTagEndExpression; QRegExp xmlAttributeStartExpression; QRegExp xmlAttributeEndExpression; QRegExp xmlAttValStartExpression; QRegExp xmlAttValEndExpression; QRegExp xmlAttValExpression; QTextCharFormat xmlProcInstFormat; QTextCharFormat xmlDoctypeFormat; QTextCharFormat xmlCommentFormat; QTextCharFormat xmlTagFormat; QTextCharFormat xmlEntityFormat; QTextCharFormat xmlAttributeFormat; QTextCharFormat xmlAttValFormat; //Enumeration for types of element, used for tracking what //we're inside while highlighting over multiline blocks. enum xmlState { inNothing, //Don't know if we'll need this or not. inProcInst, //starting with <? and ending with ?> inDoctypeDecl, //starting with <!DOCTYPE and ending with > inOpenTag, //starting with < + xmlName and ending with /?> inOpenTagName, //after < and before whitespace. Implies inOpenTag. inAttribute, //if inOpenTag, starting with /s*xmlName/s*=/s*" and ending with ". inAttName, //after < + xmlName + whitespace, and before =". Implies inOpenTag. inAttVal, //after =" and before ". May also use single quotes. Implies inOpenTag. inCloseTag, //starting with </ and ending with >. inCloseTagName,//after </ and before >. Implies inCloseTag. inComment //starting with <!-- and ending with -->. Overrides all others. }; }; #endif
Net5F/QueuedEvents
Source/Public/QueuedEvents.h
<reponame>Net5F/QueuedEvents<gh_stars>0 #pragma once #include "readerwriterqueue.h" #include <vector> #include <unordered_map> #include <mutex> #include <cstdlib> #include <utility> #include <iostream> namespace AM { /** * This header contains Dispatcher and EventQueue, which together form a * queued event dispatching system. * * Features: * Events may be any arbitrary type. * * Notifications are thread-safe and queued. * * Thread safety: * notify(), subscribe(), and unsubscribe() will block if either of the * other two are running. This means they're safe to call across threads, * but may not be perfectly performant. * * Note: It would be ideal to have the two classes in separate headers, but * we would run into circular include issues. */ // Forward declaration template<typename T> class EventQueue; //-------------------------------------------------------------------------- // EventDispatcher //-------------------------------------------------------------------------- /** * A simple event dispatcher. * * Through notify<T>(), dispatches events to any subscribed EventQueues of a * matching type T. */ class EventDispatcher { public: // See queueVectorMap comment for details. using QueueVector = std::vector<void*>; /** * Pushes the given event to all queues of type T. */ template<typename T> void push(const T& event) { // Acquire a lock before accessing a queue. std::scoped_lock lock(queueVectorMapMutex); // Get the vector of queues for type T. QueueVector& queueVector{getQueueVectorForType<T>()}; // Push the given event into all queues. for (auto& queue : queueVector) { // Cast the queue to type T. EventQueue<T>* castQueue{static_cast<EventQueue<T>*>(queue)}; // Push the event. castQueue->push(event); } } /** * Constructs the given event in place in all queues of type T. */ template<typename T, typename... Args> void emplace(Args&&... args) { // Acquire a lock before accessing a queue. std::scoped_lock lock(queueVectorMapMutex); // Get the vector of queues for type T. QueueVector& queueVector{getQueueVectorForType<T>()}; // Push the given event into all queues. for (auto& queue : queueVector) { // Cast the queue to type T. EventQueue<T>* castQueue{static_cast<EventQueue<T>*>(queue)}; // Push the event. castQueue->emplace(std::forward<Args>(args)...); } } /** * Returns the number of queues that are currently constructed for type T. * * Not thread safe. Really only useful for testing. */ template<typename T> std::size_t getNumQueuesForType() { // Get the vector of queues for type T. QueueVector& queueVector{getQueueVectorForType<T>()}; // Return the number of queues. return queueVector.size(); } private: /** Only give EventQueue access to subscribe() and unsubscribe(), so users don't get confused about how to use the interface. */ template<typename> friend class EventQueue; /** * Returns the next unique integer key value. Used by getKeyForType(). */ static int getNextKey() { static std::atomic<int> nextKey{0}; return nextKey++; } /** * Returns the vector of queues that hold type T. */ template<typename T> QueueVector& getQueueVectorForType() { // Get the key associated with type T. // Note: Static var means that getNextKey() will only be called once // per type T, and that this key will be consistent across all // Observer instances. static int key{getNextKey()}; // Return the vector at the given key. // (Constructs one if there is no existing vector.) return queueVectorMap[key]; } /** * Subscribes the given queue to receive event notifications. * * Only used by EventQueue. */ template<typename T> void subscribe(EventQueue<T>* queuePtr) { // Acquire a lock since we're going to be modifying data structures. std::scoped_lock lock(queueVectorMapMutex); // Get the vector of queues for type T. QueueVector& queueVector{getQueueVectorForType<T>()}; // Add the given queue to the vector. // Allocate the new queue and add it to the vector. queueVector.push_back(static_cast<void*>(queuePtr)); } /** * Unsubscribes the given event queue. It will no longer receive event * notifications. * * Only used by EventQueue. */ template<typename T> void unsubscribe(const EventQueue<T>* unsubQueuePtr) { // Acquire a lock since we're going to be modifying data structures. std::scoped_lock lock(queueVectorMapMutex); // Get the vector of queues for type T. QueueVector& queueVector{getQueueVectorForType<T>()}; // Search for the given queue in the vector. auto queueIt = queueVector.begin(); for (; queueIt != queueVector.end(); ++queueIt) { if (*queueIt == unsubQueuePtr) { break; } } // Error if we didn't find the queue. // Note: Since this function is only called in EventQueue's // destructor, we should expect it to always find the queue. if (queueIt == queueVector.end()) { std::cout << "Failed to find queue while unsubscribing." << std::endl; std::abort(); } // Remove the queue at the given index. // Note: This may do some extra work to fill the gap, but there's // probably only 2-3 elements and pointers are small. queueVector.erase(queueIt); } /** A map of integer keys -> vectors of event queues. We store each EventQueue<T> as a void pointer so that they can share a vector, then cast them to the appropriate type in our templated functions. */ std::unordered_map<int, QueueVector> queueVectorMap; /** Used to lock access to the queueVectorMap. */ std::mutex queueVectorMapMutex; }; //-------------------------------------------------------------------------- // EventQueue //-------------------------------------------------------------------------- /** * A simple event listener queue. * * Supports pushing events into the queue (done by Dispatcher), and popping * events off the queue. */ template<typename T> class EventQueue { public: EventQueue(EventDispatcher& inDispatcher) : dispatcher{inDispatcher} { dispatcher.subscribe(this); } ~EventQueue() { // Note: This acquires a write lock, don't destruct this queue unless // you don't mind potentially waiting. dispatcher.unsubscribe<T>(this); } /** * Attempts to pop the front event from the queue. * * @return true if an event was available, else false. */ bool pop(T& event) { // Try to pop an event. return queue.try_dequeue(event); } /** * Override that removes the front event of the queue without returning * it. * * @return true if an event was available, else false. */ bool pop() { return queue.pop(); } /** * Attempts to pop the front event from the queue, blocking and waiting * for up to timeoutUs microseconds before returning false if one is not * available. * * A negative timeoutUs causes an indefinite wait. * * @return true if an event was available, else false if we timed out. */ bool waitPop(T& event, std::int64_t timeoutUs) { return queue.wait_dequeue_timed(event, timeoutUs); } /** * @return If the queue is empty, returns nullptr. Else, returns a pointer * to the front event of the queue (the one that would be removed by the * next call to pop()). */ T* peek() const { return queue.peek(); } /** * Returns the number of elements in the queue. */ std::size_t size() { return queue.size_approx(); } private: /** Only give EventDispatcher access to push(), so users don't get confused about how to use the interface. */ friend class EventDispatcher; /** * Pushes the given event into the queue. * * Errors if a memory allocation fails while pushing the event into the * queue. */ void push(const T& event) { // Push the event into the queue. if (!(queue.enqueue(event))) { std::cout << "Memory allocation failed while pushing an event." << std::endl; std::abort(); } } /** * Passes the given event to the queue, to be constructed in place. * * Errors if a memory allocation fails while pushing the event into the * queue. */ template<typename... Args> void emplace(Args&&... args) { // Push the event into the queue. if (!(queue.emplace(std::forward<Args>(args)...))) { std::cout << "Memory allocation failed while pushing an event." << std::endl; std::abort(); } } /** A reference to our parent dispatcher. */ EventDispatcher& dispatcher; /** The event queue. Holds events that have been pushed into it by the dispatcher. */ moodycamel::BlockingReaderWriterQueue<T> queue; }; } // End namespace AM
Cassidy/mks
include/kernel/kernel.h
/********************************************* * File name: kernel.h * Author: Cassidy * Time-stamp: <2011-05-19 20:09:15> ********************************************* */ #ifndef _KERNEL_H #define _KERNEL_H #include <config.h> #include <unistd.h> #include <kernel/printk.h> #define PAGE_SIZE 4096 #endif
Cassidy/mks
driver/character/keyboard.c
<reponame>Cassidy/mks /* * Program: keyboard.c * Purpose: 键盘驱动程序 * Author: mofaph <<EMAIL>> * Date: 2011-6-10 */ #include <kernel/printk.h> /* printk */ #include <asm/io.h> /* inb */ #include "keyboard.h" /* keymap kbdqueue MAP_COL MAKE */ static struct kbdqueue kbd; /* 键盘缓冲区队列 */ static int enqueue(unsigned char); /* 插入队列 */ static void dequeue(void); /* 出队列 */ static unsigned char headqueue(void); /* 查看队列头 */ /* 键盘中断已在 interrupt.c 中开启了 */ void keyboard_init(void) { kbd.head = kbd.tail = kbd.buf; } void do_intr_keyboard(void) { unsigned char keycode; unsigned char keymapcol = NO_SHIFT; /* NO_SHIFT = 0 */ unsigned char scan_code = inb(0x60); /* 读取扫描码 */ if ((scan_code & 0x80) == MAKE) { if ((scan_code != SHIFT_L) && (scan_code != SHIFT_R)) { if ((keycode = headqueue()) == SHIFT_L || keycode == SHIFT_R) keymapcol = WITH_SHIFT; printchar(keymap[scan_code*MAP_COL+keymapcol]); /* MAP_COL=3 */ } else if ((scan_code == SHIFT_L) || (scan_code == SHIFT_R)) { enqueue(scan_code); } else /* do nothing */; } else if ((scan_code & 0x80) == BREAK) { if (((scan_code & 0x7F) == SHIFT_L) || ((scan_code & 0x7F) == SHIFT_R)) dequeue(); } else /* do nothing */; /* 复位 8259A 的正在服务寄存器(ISR)。 因为在 setup 中设置 8259A 工作在非自动结束方式,主芯片 IRQ2 连接从芯片, 所以复位时要把 IRQ2 置位,其余的都复位。8259A 主芯片的端口地址是 0x20 */ outb_p(0x20, 0x20); /* outb_p(value, port) */ } /* enqueue: 插入键盘缓冲区队列 */ static int enqueue(unsigned char code) { /* 键盘缓冲区队列已满,则不能插入 */ if (kbd.tail == kbd.buf + KBD_BUF_SIZE) return -1; *kbd.tail++ = code; return 0; } /* dequeue: 队列为空时返回;队列非空时,返回队列头元素 */ static void dequeue(void) { if (kbd.tail == kbd.buf) return; if (kbd.head == kbd.tail && kbd.head != kbd.buf) { kbd.head = kbd.tail = kbd.buf; return; } kbd.head++; } /* headqueue: 查看队列头;队列为空时,返回 0 */ static unsigned char headqueue(void) { if (kbd.tail == kbd.head) return 0; return *kbd.head; }
Cassidy/mks
include/asm/system.h
<reponame>Cassidy/mks<gh_stars>1-10 /********************************************* * File name: system.h * Author: Cassidy * Time-stamp: <2011-05-09 23:06:36> ********************************************* */ #ifndef _SYSTEM_H #define _SYSTEM_H #define sti() __asm__ ("sti"::) #define cli() __asm__ ("cli"::) #define nop() __asm__ ("nop"::) #define iret() __asm__ ("iret"::) /* gcc 嵌入汇编格式说明: asm("汇编语句" : 输出寄存器 : 输入寄存器 : 会被修改的寄存器); 嵌入汇编程序规定,把输出和输入寄存器统一按顺序编号,顺序是从寄存器序列从左到右 从上到下以“%0”开始,分别记为“%0、%1、……%9”。 */ #define move_to_user_mode() \ __asm__("movl %%esp,%%eax\n\t" \ "pushl $0x17\n\t" \ "pushl %%eax\n\t" \ "pushfl\n\t" \ "pushl $0x0F\n\t" \ "pushl $1f\n\t" \ "iret\n\t" \ "1:\tmovl $0x17, %%eax\n\t" \ "movw %%ax, %%ds\n\t" \ "movw %%ax, %%es\n\t" \ "movw %%ax, %%fs\n\t" \ "movw %%ax, %%gs" \ :::"ax") /* 嵌入汇编代码说明: a 使用寄存器 eax d 使用寄存器 edx i ??? o 使用内存地址可以加偏移值 gate_addr: 门描述符的起始地址 type: 门描述符的类型标志 dpl: 特权级 addr: 过程入口点偏移值(32位) */ #define _set_gate(gate_addr,type,dpl,addr) \ __asm__ ("movw %%dx,%%ax\n\t" /* 设置 eax 的低 16 位 */ \ "movw %0,%%dx\n\t" /* 设置 edx 的低 16 位 */ \ "movl %%eax,%1\n\t" /* eax: 中断描述符低 32 位 */ \ "movl %%edx,%2" /* edx: 中断描述符高 32 位 */ \ : \ : "i" ((short) (0x8000+(dpl<<13)+(type<<8))), /* P=1 */ \ "o" (*((char *) (gate_addr))), \ "o" (*(4+(char *) (gate_addr))), \ "d" ((char *) (addr)),"a" (0x00080000)) /* n: 在中断描述符表中的位置; addr: 过程入口点偏移值(32位) */ #define set_intr_gate(n,addr) _set_gate(idt + n, 14, 0, addr) #define set_trap_gate(n,addr) _set_gate(idt + n,15,0,addr) #define set_system_gate(n,addr) _set_gate(idt + n,15,3,addr) #define _set_ldt_seg_desc(gate_addr,type,base,limit) { \ *(gate_addr) = (((base) & 0x0000ffff)<<16) | \ ((limit) & 0x0ffff); \ *((gate_addr)+1) = ((base) & 0xff000000) | \ (((base) & 0x00ff0000)>>16) | \ ((limit) & 0xf0000) | \ (0x00C0F000) | \ ((type)<<8); } #define set_ldt_cs_desc(gate_addr,base,limit) \ _set_ldt_seg_desc(gate_addr,0x0A,base,limit) #define set_ldt_ds_desc(gate_addr,base,limit) \ _set_ldt_seg_desc(gate_addr,0x02,base,limit) /* %0 -- eax %1 -- 2B 段限长(15...0) %2 -- 2B 段基地址(15...0) %3 -- 1B 段基地址(23...16) %4 -- 1B 属性标志 %5 -- 1B 颗粒度+AVL+段限长(19...16) %6 -- 1B 段基地址(31...24) */ #define _set_tssldt_desc(n,addr,type) \ __asm__ ("movw $104,%1\n\t" \ "movw %%ax,%2\n\t" \ "rorl $16,%%eax\n\t" \ "movb %%al,%3\n\t" \ "movb $"type",%4\n\t" \ "movb $0x00,%5\n\t" \ "movb %%ah,%6\n\t" \ "rorl $16,%%eax" \ : \ :"a" (addr), "m" (*(n)), "m" (*(n+2)), "m" (*(n+4)), \ "m" (*(n+5)), "m" (*(n+6)), "m" (*(n+7)) \ ) #define set_tss_desc(n,addr) _set_tssldt_desc(((char *) (n)),addr,"0x89") #define set_ldt_desc(n,addr) _set_tssldt_desc(((char *) (n)),addr,"0x82") #endif
Cassidy/mks
lib/message.c
/********************************************* * File name: message.c * Author: Cassidy * Time-stamp: <2011-06-10 14:45:55> ********************************************* */ #include <unistd.h> long * get_msg_entry(struct Msg * msgpt) { long entry; entry = (long)msgpt; entry = (entry & 0xFFFFF000) + 0x1000; return (long *)entry; } long small_msg_send(long * destination, long * msgpt) { long res = 1; __asm__ volatile ( \ "int $0x80" \ :"=a"(res) \ :"0"(res), "b"(*destination), "c"(*msgpt)); if(res == 1) return 1; return -1; } long small_msg_receive(long * source, long * msgpt) { long res = 2; long msg; long src; __asm__ volatile ( \ "int $0x80" \ :"=a"(res), "=b"(src), "=c"(msg) \ :"0"(res), "b"(*source)); if(res == 1) { *msgpt = msg; *source = src; return 1; } return -1; } long big_msg_send(long * destination, struct Msg * msgpt) { long res = 3; __asm__ volatile ( \ "int $0x80" \ :"=a"(res) \ :"0"(res), "b"(*destination), "c"((long)msgpt)); if(res == 1) return 1; return -1; } long big_msg_receive(long * source, struct Msg * msgpt) { long res = 4; long src; __asm__ volatile ( \ "int $0x80" \ :"=a"(res), "=b"(src) \ :"0"(res), "b"(*source), "c"((long)msgpt)); if(res == 1) { *source = src; return 1; } return -1; }
Cassidy/mks
include/kernel/proc.h
/********************************************* * File name: proc.h * Author: Cassidy * Time-stamp: <2011-05-26 18:23:53> ********************************************* */ #ifndef _PROC_H #define _PROC_H #include <kernel/kernel.h> #include <kernel/head.h> /* desc_struct */ #define RUNNING 0 #define SLEEPING 1 #define ZOMBIE 2 #define FIRST_TSS_ENTRY 4 #define FIRST_LDT_ENTRY 5 /* 第 n 个 TSS 和 LDT 在全局描述符表的偏移位置 */ #define TSS(n) ((((unsigned long)(n))<<4) + (FIRST_TSS_ENTRY<<3)) #define LDT(n) ((((unsigned long)(n))<<4) + (FIRST_LDT_ENTRY<<3)) #define ltr(n) __asm__("ltr %%ax"::"a"(TSS(n))) /* 加载第 n 个任务状态段寄存器 */ #define lldt(n) __asm__("lldt %%ax"::"a"(LDT(n))) /* 加载第 n 个局部描述符表寄存器 */ struct i387_struct { long cwd; long swd; long twd; long fip; long fcs; long foo; long fos; long st_space[20]; }; /* 任务状态段结构体 */ struct tss_struct { long back_link; /* 先前任务链接字段,含有前一个任务 TSS 段选择符 */ long esp0; long ss0; long esp1; long ss1; long esp2; long ss2; long cr3; long eip; long eflags; long eax, ecx, edx, ebx; long esp; long ebp; long esi; long edi; long es; long cs; long ss; long ds; long fs; long gs; long ldt; long trace_bitmap; /* 31...16 -- I/O位图基地址, 0 -- 调试陷阱标志 */ struct i387_struct i387; }; /* 进程结构体 */ struct proc_struct { int proc_type; /* 进程类型(0-无效, 1-Task, 2-Server, 3-User) */ long state; /* 运行状态 */ long counter; /* 运行时间计数 */ int exit_code; /* 进程停止执行后的退出码 */ unsigned long start_code; unsigned long end_code; unsigned long end_data; unsigned long brk; /* 总长度(字节数) */ unsigned long start_stack; long pid; /* 进程号 */ long father; /* 父进程号 */ long pgrp; /* 进程组号 */ long session; /* 会话号 */ long leader; /* 会话首领号 */ unsigned uid; /* 用户 id */ unsigned euid; /* 有效用户 id */ unsigned suid; /* 保存的用户 id */ unsigned gid; /* 组 id */ unsigned egid; /* 有效组 id */ unsigned sgid; /* 保存的组 id */ long alarm; /* 用户态运行时间(滴答数) */ long utime; /* 内核态运行时间(滴答数) */ long stime; long cutime; long cstime; long start_time; /* 进程开始运行时刻 */ unsigned short used_math; /* 是否使用了协处理器 */ int tty; struct proc_struct * next_ready; /* 在进程队列的下一个进程 */ /* 局部描述符表(0-空, 1-代码段, 2-数据段) desc_struct -- include/kernel/head.h */ struct desc_struct ldt[3]; struct tss_struct tss; /* 进程的任务状态段信息结构 */ }; #define switch_to(n) { \ struct {long a,b;} _tmp; \ __asm__("cmpl %%ecx, proc_current\n\t" \ "je 1f\n\t" \ "movw %%dx, %1\n\t" \ "xchgl %%ecx, proc_current\n\t" \ "ljmp %0\n\t" \ "1:" \ ::"m"(*&_tmp.a), "m"(*&_tmp.b), \ "d"(TSS(n)), "c"((long)proc[n])); \ } #define INIT_PROC_DATA \ {0, /* proc_type */ \ 0, /* state */ \ 0, /* counter */ \ 0, /* exit_code */ \ 0, /* start_code */ \ 0, /* end_code */ \ 0, /* end_data */ \ 0, /* brk */ \ 0, /* start_stack */ \ 0, /* pid */ \ -1, /* father */ \ 0, /* pgrp */ \ 0, /* session */ \ 0, /* leader */ \ 0, /* uid */ \ 0, /* euid */ \ 0, /* suid */ \ 0, /* gid */ \ 0, /* egid */ \ 0, /* sgid */ \ 0, /* alarm */ \ 0, /* utime */ \ 0, /* stime */ \ 0, /* cutime */ \ 0, /* cstime */ \ 0, /* start_time */ \ 0, /* used_math */ \ -1, /* tty */ \ NULL, /* next_reader */ \ \ /* ldt */ \ {{0,0},{0,0},{0,0}}, \ \ /* tss */ \ { \ 0, /* back_link */ \ 0, /* esp0 */ \ 0x10, /* ss0 */ \ 0, /* esp1 */ \ 0, /* ss1 */ \ 0, /* esp2 */ \ 0, /* ss2 */ \ PAGE_DIR_ADDR, /* cr3 */ \ 0, /* eip */ \ 0, /* eflags */ \ 0, /* eax */ \ 0, /* ecx */ \ 0, /* edx */ \ 0, /* ebx */ \ 0, /* esp */ \ 0, /* ebp */ \ 0, /* esi */ \ 0, /* edi */ \ 0x17, /* es */ \ 0x0F, /* cs */ \ 0x17, /* ss */ \ 0x17, /* ds */ \ 0x17, /* fs */ \ 0x17, /* gs */ \ 0, /* ldt */ \ 0x80000000, /* trace_bitmap */ \ {} /* i387 */ \ }} #endif
Cassidy/mks
lib/errno.c
<filename>lib/errno.c /********************************************* * File name: errno.c * Author: Cassidy * Time-stamp: <2011-05-12 20:05:47> ********************************************* */ int errno;
Cassidy/mks
include/kernel/time.h
/********************************************* * File name: time.h * Author: Cassidy * Time-stamp: <2011-04-19 20:11:28> ********************************************* */ #ifndef _TIME_H #define _TIME_H struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; }; #endif
Cassidy/mks
kernel/time.c
/********************************************* * File name: time.c * Author: Cassidy * Time-stamp: <2011-06-10 16:24:00> ********************************************* */ #include <kernel/kernel.h> #include <asm/io.h> #include <kernel/time.h> /* tm */ #include <kernel/proc.h> /* proc_struct */ /* outb_p(value, port) inb_p(port) -- include/asm/io.h CMOS 的地址空间在基本地址空间之外,因此其中不包括可执行代码。要访问它需要通过 端口 0x70、0x71 进行。0x70 是地址端口,0x71 是数据端口。为了读取指定 偏移位置的字节,必须首先使用 out 指令向地址端口 0x70 发送指定字节的偏移 位置值,然后使用 in 指令从数据端口 0x71 读取指定的字节信息。同样,对于写操作 也需要首先向地址端口 0x70 发送指定字节的偏移值,然后把数据写到数据端口 0x71。 */ #define CMOS_READ(addr) ({ \ outb_p(0x80 | addr, 0x70); \ inb_p(0x71); \ }) /* BCD 码利用半个字节(4位)表示一个十进制数,因此一个字节表示两个十进制数。 (val)&15 取 BCD 表示的十进制个位数,而 (val)>>4 取 BCD 表示的十进制 十位数,再乘以 10。因此最后两者相加就是一个字节 BCD 码的实际二进制数值。 */ #define BCD_TO_BIN(val) ((val) = ((val)&15)+((val)>>4)*10) #define MINUTE 60 #define HOUR (60*MINUTE) #define DAY (24*HOUR) #define YEAR (365*DAY) long volatile jiffies; long startup_time = 0; extern void schedule(void); /* 进程调度(kernel/proc.c) */ extern struct proc_struct * proc_current; /* 当前进程指针(include/kernel/proc.h) */ /* interestingly, we assume leap-years */ static int month[12] = { 0, DAY*(31), DAY*(31+29), DAY*(31+29+31), DAY*(31+29+31+30), DAY*(31+29+31+30+31), DAY*(31+29+31+30+31+30), DAY*(31+29+31+30+31+30+31), DAY*(31+29+31+30+31+30+31+31), DAY*(31+29+31+30+31+30+31+31+30), DAY*(31+29+31+30+31+30+31+31+30+31), DAY*(31+29+31+30+31+30+31+31+30+31+30) }; /* kernel_mktime: 计算开机时间 */ long kernel_mktime(struct tm * tm) { long res; int year; /* 从 UNIX 诞生(1970)到现在经过的时间 */ /* 因为是两位表示方式,会有 2000年 问题。可以加上 100 暂时解决这个问题。 但是,到了 2100 年,这段程序如果还在使用,就得重写。 */ if(tm->tm_year < 70) tm->tm_year += 100; year = tm->tm_year - 70; /* magic offsets (y+1) needed to get leapyears right.*/ res = YEAR*year + DAY*((year+1)/4); res += month[tm->tm_mon]; /* and (y+2) here. If it wasn't a leap-year, we have to adjust */ if (tm->tm_mon>1 && ((year+2)%4)) res -= DAY; res += DAY*(tm->tm_mday-1); res += HOUR*tm->tm_hour; res += MINUTE*tm->tm_min; res += tm->tm_sec; return res; } /* time_init: 时间初始化 */ void time_init(void) { struct tm time; /* tm -- include/kernel/time.h */ do { time.tm_sec = CMOS_READ(0); time.tm_min = CMOS_READ(2); time.tm_hour = CMOS_READ(4); time.tm_mday = CMOS_READ(7); time.tm_mon = CMOS_READ(8); time.tm_year = CMOS_READ(9); } while (time.tm_sec != CMOS_READ(0)); BCD_TO_BIN(time.tm_sec); BCD_TO_BIN(time.tm_min); BCD_TO_BIN(time.tm_hour); BCD_TO_BIN(time.tm_mday); BCD_TO_BIN(time.tm_mon); BCD_TO_BIN(time.tm_year); time.tm_mon--; /* tm_mon 中月份范围是 0~11 */ startup_time = kernel_mktime(&time); jiffies = 0; /* 宏函数 outb_p(value, port) inb_p(port) -- include/asm/io.h */ outb_p(0x36, 0x43); outb_p(LATCH & 0xFF, 0x40); /* LATCH -- include/config.h */ outb_p(LATCH >> 8, 0x40); outb(inb_p(0x21)&~0x01, 0x21); } /* do_intr_clock: 时钟中断处理程序 */ void do_intr_clock(long *eip, long error_code, long cpl) { jiffies++; /* 由于初始化中断控制芯片时没有采用自动EOI,所以这里需要发指令结束该硬件中断 */ outb(0x20, 0x20); if (cpl != 0) proc_current->utime++; else /* cpl == 0 */ proc_current->stime++; if((--(proc_current->counter)) > 0) return; proc_current->counter = 0; if(cpl == 0) return; schedule(); }
Cassidy/mks
lib/fork.c
<gh_stars>1-10 /********************************************* * File name: fork.c * Author: Cassidy * Time-stamp: <2011-05-11 23:57:52> ********************************************* */ void fork(void) { __asm__("int $0x80"); }
Cassidy/mks
kernel/proc.c
<reponame>Cassidy/mks<filename>kernel/proc.c /********************************************* * File name: proc.c * Author: Cassidy * Time-stamp: <2011-06-10 16:03:27> ********************************************* */ #include <kernel/kernel.h> /* PAGE_SIZE */ #include <kernel/proc.h> /* proc_struct INIT_PROC_DATA ltr lldt FIRST_TSS_ENTRY */ #include <asm/system.h> /* set_tss_desc set_ldt_desc set_ldt_cs_desc set_ldt_ds_desc */ struct desc_struct *gdt; /* 全局描述符表的入口地址 */ union proc_union { /* 进程控制体与其内核态堆栈,总共4KB */ struct proc_struct proc; /* proc_struct -- include/kernel/proc.h */ char stack[PAGE_SIZE]; /* PAGE_SIZE=4096 (include/kernel/kernel.h) */ }; /* NR_INIT_PROCS=3, INIT_PROC_DATA (include/config.h) */ union proc_union init_procs[NR_INIT_PROCS] = { {INIT_PROC_DATA,}, }; /* NR_PROCS=64(include/config.h) */ struct proc_struct * proc[NR_PROCS]; /* 所有进程指针 */ struct proc_struct * task_head; /* 任务队列头指针 */ struct proc_struct * task_tail; /* 任务队列尾指针 */ struct proc_struct * server_head; /* 服务器队列头指针 */ struct proc_struct * server_tail; /* 服务器队列尾指针 */ struct proc_struct * user_head; /* 用户进程队列头指针 */ struct proc_struct * user_tail; /* 用户进程队列尾指针 */ struct proc_struct * proc_current; /* 当前进程指针 */ extern void idle(void); /* idle进程入口 (kernel/main.c) */ extern void init_proc(void); /* init进程入口 (kernel/init_proc.c) */ extern void system_task(void); /* system进程入口 (system_task/system.c) */ extern int share_multi_pages(unsigned long from, unsigned long to, long amount); /* kernel/memory.c */ /* 进程初始化 */ void proc_init(void) { int i,j; unsigned long *pp, *qq; struct desc_struct * p; /* desc_struct -- include/kernel/head.h */ gdt = GDT_ADDR; /* GDT_ADDR = 0x6800 (include/config.h) */ for(i=0; i<NR_PROCS; i++) /* NR_PROCS = 64 (include/config) */ proc[i] = NULL; p = gdt + FIRST_TSS_ENTRY; /* FIRST_TSS_ENTRY=4 (include/kernel/proc.h) */ /* 初始化进程的局部描述符和状态描述符 */ for(i=0; i<NR_PROCS*2; i++,p++) p->a = p->b = 0; /* 初始化 3 个进程,进程号依次是 0 1 2 */ for(i=0; i<NR_INIT_PROCS; i++) { /* NR_INIT_PROCS=3 (include/config.h) */ proc[i] = (struct proc_struct *)&(init_procs[i]); /*******************************************/ /* 不知为什么,使用不了*proc[i] = *proc[0]方式赋值。使用下面的语句实现 */ pp = (unsigned long *)proc[i]; qq = (unsigned long *)proc[0]; for(j=0; j<(PAGE_SIZE>>2); j++) *(pp++) = *(qq++); /*******************************************/ proc[i]->pid = i; proc[i]->tss.esp0 = PAGE_SIZE + (long)proc[i]; /* PAGE_SIZE=4096 -- include/kernel/kernel.h */ proc[i]->tss.ldt = LDT(i); /* LDT(n) -- include/kernel/proc.h */ proc[i]->tss.esp = 0x4000000; /* 用户堆栈指针,指向64M末 */ proc[i]->tss.ebp = proc[i]->tss.esp; /* 以下四个宏函数在 include/asm/system.h 里定义 */ set_tss_desc(gdt + FIRST_TSS_ENTRY + i*2, &(proc[i]->tss)); set_ldt_desc(gdt + FIRST_LDT_ENTRY + i*2, &(proc[i]->ldt)); set_ldt_cs_desc((long *)&(proc[i]->ldt[1]), 0x4000000*i, 16384); /* limit=64M/4K=16*1024=16384 */ set_ldt_ds_desc((long *)&(proc[i]->ldt[2]), 0x4000000*i, 16384); /* 共享多个物理页面, 线性地址分别分 0 和 0x4000000*i, 共享页面个数为 640KB/4KB=160 */ if(i != 0) share_multi_pages(0, 0x4000000*i, 160); } PROC_INIT; /* include/config.h */ task_head = task_tail = NULL; server_head = server_tail = NULL; user_head = user_tail = NULL; proc_current = proc[PROC_IDLE_NR]; /* PROC_IDLE_NR=0 (include/config.h) */ __asm__("pushfl; andl $0xFFFFBFFF, (%esp); popfl"); /* 任务嵌套标志置零 */ ltr(PROC_IDLE_NR); /* ltr(n) -- include/kernel/proc.h */ lldt(PROC_IDLE_NR); /* lldt(n) -- include/kernel/proc.h */ } /* 增加可运行进程到等待队列 */ void add_running_proc(void) { int i; int flag = 0; struct proc_struct ** proc_head; struct proc_struct ** proc_tail; struct proc_struct * proc_temp; for(i=1; i<NR_PROCS; i++) { if(proc[i] && (proc[i]->state==RUNNING) && proc[i]!=proc_current) { if(proc[i]->proc_type == 1) { proc_head = &task_head; proc_tail = &task_tail; } else if(proc[i]->proc_type == 2) { proc_head = &server_head; proc_tail = &server_tail; } else if(proc[i]->proc_type == 3) { proc_head = &user_head; proc_tail = &user_tail; } proc_temp = *proc_head; if(!proc_temp) { *proc_head = *proc_tail = proc[i]; proc[i]->next_ready = NULL; continue; } while(proc_temp) { if(proc_temp->pid == i) { flag = 1; break; } proc_temp = proc_temp->next_ready; } if(flag == 0) { (*proc_tail)->next_ready = proc[i]; *proc_tail = proc[i]; proc[i]->next_ready = NULL; } flag = 0; } } } /* 进程调度函数 */ void schedule(void) { int next = 0; int current_type = proc_current->proc_type; int flag = current_type; int counter = COUNTER; /* 时间片大小 */ add_running_proc(); /* 增加可运行进程到等待队列 */ if(proc_current->state != RUNNING) flag = 3; /* 选出一个合适的进程准备运行 */ if(task_head) { next = task_head->pid; task_head = task_head->next_ready; if(!task_head) task_tail = NULL; } else if(server_head && (flag>1)) { next = server_head->pid; server_head = server_head->next_ready; if(!server_head) server_tail = NULL; } else if(user_head && (flag>2)) { next = user_head->pid; user_head = user_head->next_ready; if(!user_head) user_tail = NULL; } /* 如果没有其它进程可选且当前进程是running状态,则返回 */ if((next==0) && (proc_current->state==RUNNING)) { if(proc_current->pid != 0) proc_current->counter = counter; return; } /* 如果没有其它进程可选且当前进程不是running状态,则切换到idle进程 */ else if((next==0) && (proc_current->state!=RUNNING)) counter = 0; /* 如果当前进程是running状态,将它插入就绪队列 */ else if((next!=0) && (proc_current->state==RUNNING) && (proc_current->pid!=0)) { if(current_type==1) { if(!task_head) task_head = task_tail = proc_current; else { task_tail->next_ready = proc_current; task_tail = proc_current; task_head = task_head->next_ready; } } else if(current_type==2) { if(!server_head) server_head = server_tail = proc_current; else { server_tail->next_ready = proc_current; server_tail = proc_current; server_head = server_head->next_ready; } } else if(current_type==3) { if(!user_head) user_head = user_tail = proc_current; else { user_tail->next_ready = proc_current; user_tail = proc_current; user_head = user_head->next_ready; } } proc_current->next_ready = NULL; } proc[next]->counter = counter; proc[next]->next_ready = NULL; switch_to(next); /* 切换到下一个进程 */ }
Cassidy/mks
include/kernel/message.h
/********************************************* * File name: message.h * Author: Cassidy * Time-stamp: <2011-06-10 14:44:56> ********************************************* */ #ifndef _MESSAGE_H #define _MESSAGE_H #define MSG_ANY -1 /* 消息是两页大小,其中只有与页面对齐的一个完整页面的数据是有效的 */ struct Msg { char a[4096*2]; }; #endif
Cassidy/mks
include/unistd.h
/********************************************* * File name: unistd.h * Author: Cassidy * Time-stamp: <2011-06-10 14:25:54> ********************************************* */ #ifndef _UNISTD_H #define _UNISTD_H #include <kernel/message.h> #ifndef NULL #define NULL ((void *) 0) //定义空指针 #endif extern int errno; long * get_msg_entry(struct Msg * msgpt); long small_msg_send(long * destination, long * msgpt); long small_msg_receive(long * source, long * msgpt); long big_msg_send(long * destination, struct Msg * msgpt); long big_msg_receive(long * source, struct Msg * msgpt); int fork(void); #endif
Cassidy/mks
include/kernel/printk.h
/********************************************* * File name: printk.h * Author: Cassidy * Time-stamp: <2011-05-10 21:40:02> ********************************************* */ #ifndef _PRINTK_H #define _PRINTK_H /* 以下的函数都在 kernel/printk.c 中定义 */ extern void con_init(void); /* 显示初始化 */ extern int printk(const char *); /* 输出字符串 */ extern int prints(const char *); /* 输出字符串 */ extern void printa(const long a); /* 输出长整型变量 */ extern void printbin(const unsigned long); /* 输出二进制数 */ extern void printchar(unsigned char c); /* 显示字符 */ extern void printhex(unsigned char c); /* 显示十六进制数 */ #endif
Cassidy/mks
kernel/main.c
/********************************************* * File name: main.c * Author: Cassidy * Time-stamp: <2011-06-10 15:52:30> ********************************************* */ #include <kernel/kernel.h> #include <asm/system.h> /* sti move_to_user_mode */ #define MEM_SIZE (*(unsigned long *)0x90000) /* RAM 内存总量 */ extern void mem_init(unsigned long start, unsigned long end); /* 内存初始化(kernel/memory.c) */ extern void intr_init(void); /* 中断初始化(kernel/interrupt.c) */ extern void time_init(void); /* 时间初始化(time.c) */ extern void proc_init(void); /* 进程初始化(proc.c) */ extern void msg_init(void); /* 消息传递初始化(messaging.c) */ extern void keyboard_init(void); /* 键盘初始化(driver/character/keyboard.c) */ /* 物理地址应该不可能出现负数 */ static unsigned long memory_end = 0; /* 机器具有的物理内存容量(字节数) */ static unsigned long buffer_memory_end = 0; /* 高速缓冲区末端地址 */ static unsigned long main_memory_start = 0; /* 主内存(将用于分页)开始的位置 */ void main(void) { con_init(); /* 显示初始化 */ memory_end = MEM_SIZE; /* RAM 内存总量 */ memory_end &= 0xFFFFF000; /* 忽略不到4KB(1页)的内存数 */ if(memory_end > 64*1024*1024) /* 如果内存量超过64MB,则按64MB计 */ memory_end = 64*1024*1024; if(memory_end > 12*1024*1024) /* 如果内存>12MB,则设置缓冲区末端=4MB */ buffer_memory_end = 4*1024*1024; else if(memory_end > 6*1024*1024) /* 否则若内存>6MB,则设置缓冲区末端=2MB */ buffer_memory_end = 2*1024*1024; else /* 1M < memory_end && memory_end <= 6M */ buffer_memory_end = 1*1024*1024; /* 否则设置缓冲区末端=1MB */ main_memory_start = buffer_memory_end; /* 主内存起始位置=缓冲区末端 */ mem_init(main_memory_start, memory_end); /* 主内存初始化(kernel/memory.c) */ intr_init(); /* 中断初始化(kernel/interrupt.c) */ time_init(); /* 时间初始化(kernel/time.c) */ proc_init(); /* 进程初始化(kernel/proc.c) */ msg_init(); /* 消息传递初始化(kernel/messaging.c) */ keyboard_init(); /* 键盘初始化(driver/character/keyboard.c) */ sti(); /* include/asm/system.h */ move_to_user_mode(); /* include/asm/system.h */ idle(); } /* idle进程入口 */ void idle(void) {while (1);}
Cassidy/mks
system_task/system.c
/********************************************* * File name: system.c * Author: Cassidy * Time-stamp: <2011-06-10 14:56:05> ********************************************* */ #include <unistd.h> void system_task(void) { struct Msg msg; long src = MSG_ANY; while(1) { big_msg_receive(&src, &msg); src = MSG_ANY; } }
Cassidy/mks
kernel/messaging.c
<reponame>Cassidy/mks<filename>kernel/messaging.c /********************************************* * File name: messaging.c * Author: Cassidy * Time-stamp: <2011-06-10 16:15:55> ********************************************* */ #include <kernel/kernel.h> #include <kernel/messaging.h> /* msg_struct NR_MSG_HARDWARE */ #include <kernel/proc.h> extern struct proc_struct * proc[NR_PROCS]; /* 所有进程指针 -- kernel/proc.c */ extern struct proc_struct * proc_current; /* 当前进程指针 -- kernel/proc.c */ extern void schedule(void); /* 进程调度 -- kernel/proc.c */ extern void share_page(unsigned long, unsigned long); /* kernel/memory.c */ struct msg_struct * small_send_head; struct msg_struct * small_send_tail; struct msg_struct * small_receive_head; struct msg_struct * small_receive_tail; struct msg_struct * big_send_head; struct msg_struct * big_send_tail; struct msg_struct * big_receive_head; struct msg_struct * big_receive_tail; /* NR_MSG_HARDWARE=1024 (include/kernel/messaging.h) */ struct msg_struct msg_hardware[NR_MSG_HARDWARE]; /* 硬件中断消息 */ /* 消息传递初始化 */ void msg_init(void) { long i; small_send_head = small_send_tail = NULL; small_receive_head = small_receive_tail = NULL; big_send_head = big_send_tail = NULL; big_receive_head = big_receive_tail = NULL; for(i=0; i<NR_MSG_HARDWARE; i++) { msg_hardware[i].src = 0; msg_hardware[i].dest = 0; msg_hardware[i].msg = 0; msg_hardware[i].next = NULL; } } /* 发送小消息处理 */ long small_send(long src, long * dest, long * msg) { struct msg_struct * msg_p = small_receive_head; struct msg_struct * msg_t = NULL; if((src<0 && src!=MSG_HARDWARE) || src>=NR_PROCS) return -1; if(*dest < 0 || *dest >= NR_PROCS) return -1; while(msg_p) { if(*dest==msg_p->dest && (src==*((long *)(msg_p->src)) || *((long *)(msg_p->src))==MSG_ANY)) break; msg_t = msg_p; msg_p = msg_p->next; } if(msg_p) { *((long *)(msg_p->msg)) = *msg; if(*((long *)(msg_p->src)) == MSG_ANY) *((long *)(msg_p->src)) = src; if(!msg_t) small_receive_head = msg_p->next; else msg_t->next = msg_p->next; if(!msg_p->next) small_receive_tail = msg_t; proc[msg_p->dest]->state = RUNNING; schedule(); return 1; } msg_p = small_send_head; while(msg_p) { if(*dest==msg_p->src && src==msg_p->dest) return -1; msg_p = msg_p->next; } msg_p = big_send_head; while(msg_p) { if(*dest==msg_p->src && src==msg_p->dest) return -1; msg_p = msg_p->next; } msg_p = big_receive_head; while(msg_p) { if(*dest==msg_p->dest && src==*((long *)(msg_p->src))) return -1; msg_p = msg_p->next; } msg_p = NULL; if(src == MSG_HARDWARE) { int i; for(i=0; i<NR_MSG_HARDWARE; i++) if(msg_hardware[i].src != MSG_HARDWARE) { msg_p = &msg_hardware[i]; break; } if(!msg_p) return -1; } else { struct msg_struct new_msg; msg_p = &new_msg; } msg_p->src = src; msg_p->dest = *dest; msg_p->msg = *msg; msg_p->next = NULL; if(!small_send_head) small_send_head = small_send_tail = msg_p; else { small_send_tail->next = msg_p; small_send_tail = msg_p; } if(src != MSG_HARDWARE) proc[src]->state = SLEEPING; schedule(); return 1; } /* 接收小消息处理 */ long small_receive(long * src, long dest, long * msg) { struct msg_struct * msg_p = small_send_head; struct msg_struct * msg_t = NULL; if((*src<0 && *src!=MSG_ANY && *src!=MSG_HARDWARE) || *src>=NR_PROCS) return -1; if(dest < 0 || dest >= NR_PROCS) return -1; while(msg_p) { if(dest==msg_p->dest && (*src==msg_p->src || *src==MSG_ANY)) break; msg_t = msg_p; msg_p = msg_p->next; } if(msg_p) { *msg = msg_p->msg; if(*src == MSG_ANY) *src = msg_p->src; if(!msg_t) small_send_head = msg_p->next; else msg_t->next = msg_p->next; if(!msg_p->next) small_send_tail = msg_t; if(msg_p->src == MSG_HARDWARE) msg_p->src = 0; else proc[msg_p->src]->state = RUNNING; schedule(); return 1; } msg_p = small_receive_head; while(msg_p) { if(dest==*((long *)(msg_p->src)) && *src==msg_p->dest) return -1; msg_p = msg_p->next; } msg_p = big_send_head; while(msg_p) { if(dest==msg_p->dest && *src==msg_p->src) return -1; msg_p = msg_p->next; } msg_p = big_receive_head; while(msg_p) { if(dest==*((long *)(msg_p->src)) && *src==msg_p->dest) return -1; msg_p = msg_p->next; } struct msg_struct new_msg; msg_p = &new_msg; msg_p->src = (long)src; msg_p->dest = dest; msg_p->msg = (long)msg; msg_p->next = NULL; if(!small_receive_head) small_receive_head = small_receive_tail = msg_p; else { small_receive_tail->next = msg_p; small_receive_tail = msg_p; } proc[dest]->state = SLEEPING; schedule(); return 1; } /* 发送大消息处理 */ long big_send(long src, long * dest, long * msg) { struct msg_struct * msg_p = big_receive_head; struct msg_struct * msg_t = NULL; if(src < 0 || src >= NR_PROCS) return -1; if(*dest < 0 || *dest >= NR_PROCS) return -1; while(msg_p) { if(*dest==msg_p->dest && (src==*((long *)(msg_p->src)) || *((long *)(msg_p->src))==MSG_ANY)) break; msg_t = msg_p; msg_p = msg_p->next; } if(msg_p) { share_page((unsigned long)(*msg), (unsigned long)(msg_p->msg)); if(*((long *)(msg_p->src)) == MSG_ANY) *((long *)(msg_p->src)) = src; if(!msg_t) big_receive_head = msg_p->next; else msg_t->next = msg_p->next; if(!msg_p->next) big_receive_tail = msg_t; proc[msg_p->dest]->state = RUNNING; schedule(); return 1; } msg_p = small_send_head; while(msg_p) { if(dest==msg_p->src && src==msg_p->dest) return -1; msg_p = msg_p->next; } msg_p = small_receive_head; while(msg_p) { if(dest==msg_p->dest && src==*((long *)(msg_p->src))) return -1; msg_p = msg_p->next; } msg_p = big_send_head; while(msg_p) { if(dest==msg_p->src && src==msg_p->dest) return -1; msg_p = msg_p->next; } struct msg_struct new_msg; msg_p = &new_msg; msg_p->src = src; msg_p->dest = *dest; msg_p->msg = *msg; msg_p->next = NULL; if(!big_send_head) big_send_head = big_send_tail = msg_p; else { big_send_tail->next = msg_p; big_send_tail = msg_p; } proc[src]->state = SLEEPING; schedule(); return 1; } /* 接收大消息处理 */ long big_receive(long * src, long dest, long * msg) { struct msg_struct * msg_p = big_send_head; struct msg_struct * msg_t = NULL; if((*src<0 && *src!=MSG_ANY) || *src>=NR_PROCS) return -1; if(dest < 0 || dest >= NR_PROCS) return -1; while(msg_p) { if(dest==msg_p->dest && (*src==msg_p->src || *src==MSG_ANY)) break; msg_t = msg_p; msg_p = msg_p->next; } if(msg_p) { share_page((unsigned long)(msg_p->msg), (unsigned long)(*msg)); if(*src == MSG_ANY) *src = msg_p->src; if(!msg_t) big_send_head = msg_p->next; else msg_t->next = msg_p->next; if(!msg_p->next) big_send_tail = msg_t; proc[msg_p->src]->state = RUNNING; schedule(); return 1; } msg_p = small_send_head; while(msg_p) { if(dest==msg_p->dest && *src==msg_p->src) return -1; msg_p = msg_p->next; } msg_p = small_receive_head; while(msg_p) { if(dest==*((long *)(msg_p->src)) && *src==msg_p->dest) return -1; msg_p = msg_p->next; } msg_p = big_receive_head; while(msg_p) { if(dest==*((long *)(msg_p->src)) && *src==msg_p->dest) return -1; msg_p = msg_p->next; } struct msg_struct new_msg; msg_p = &new_msg; msg_p->src = (long)src; msg_p->dest = dest; msg_p->msg = *msg; msg_p->next = NULL; if(!big_receive_head) big_receive_head = big_receive_tail = msg_p; else { big_receive_tail->next = msg_p; big_receive_tail = msg_p; } proc[dest]->state = SLEEPING; schedule(); return 1; } /* 消息中断处理函数 */ long do_intr_msg(long function, long * src_dest, long * msg) { long a; long cur_pid = proc_current->pid; long entry; if(cur_pid == *src_dest) return -1; /* 消息传递失败 */ if(function == 1) a = small_send(cur_pid, src_dest, msg); else if(function == 2) a = small_receive(src_dest, cur_pid, msg); else if(function == 3) { entry = *msg; entry = (entry & 0xFFFFF000) + 0x1000; /* 消息线性地址 = 消息偏移地址 + 段基地址*/ entry += cur_pid * 0x4000000; a = big_send(cur_pid, src_dest, &entry); } else if(function == 4) { entry = *msg; entry = (entry & 0xFFFFF000) + 0x1000; /* 消息线性地址 = 消息偏移地址 + 段基地址*/ entry += cur_pid * 0x4000000; a = big_receive(src_dest, cur_pid, &entry); } else return -1; /* 消息传递失败 */ return a; }
Cassidy/mks
include/config.h
<gh_stars>1-10 /********************************************* * File name: config.h * Author: Cassidy * Time-stamp: <2011-05-17 03:12:23> ********************************************* */ #ifndef _CONFIG_H #define _CONFIG_H #define HZ 100 /* PC8253 定时芯片的输入时钟频率约为 1.193180MHZ。 这里设置 8253 芯片发出中断的频率是 100HZ,也就是 10ms 发出一次时钟中断 */ #define LATCH (1193180/HZ) #define GDT_ADDR 0x6800 #define IDT_ADDR 0x6000 #define PAGE_DIR_ADDR 0x7000 #define COUNTER 10 #define PROC_IDLE_NR 0 #define PROC_INIT_NR 1 #define PROC_SYSTEM_NR 2 #define NR_PROCS 64 #define NR_INIT_TASKS 1 #define NR_INIT_SERVERS 0 #define NR_INIT_USERS 2 #define NR_INIT_PROCS (NR_INIT_TASKS + NR_INIT_SERVERS + NR_INIT_USERS) //初始化进程数,包括任务数和服务器数 /* idle 进程的类型是 3(用户进程),标志寄存器设置了 IF 中断标志 init_proc 进程的类型是 3(用户进程),标志寄存器设置了 IF 中断标志 system_task 进程的类型是 1(任务进程),标志寄存器设置了 IF 中断标志和 IOPL */ #define PROC_INIT \ { \ proc[PROC_IDLE_NR]->proc_type = 3; \ proc[PROC_IDLE_NR]->tss.eip = (long)&idle; \ proc[PROC_IDLE_NR]->tss.eflags = 0x00000202; \ proc[PROC_INIT_NR]->proc_type = 3; \ proc[PROC_INIT_NR]->tss.eip = (long)&init_proc; \ proc[PROC_INIT_NR]->tss.eflags = 0x00000202; \ proc[PROC_SYSTEM_NR]->proc_type = 1; \ proc[PROC_SYSTEM_NR]->tss.eip = (long)&system_task; \ proc[PROC_SYSTEM_NR]->tss.eflags = 0x00003202; \ } #endif
Cassidy/mks
kernel/memory.c
/********************************************* * File name: memory.c * Author: Cassidy * Time-stamp: <2011-05-26 18:36:37> ********************************************* */ #include <kernel/kernel.h> #define LOW_MEM 0x100000 /* 1M 内存开始处 */ #define PAGING_MEMORY (64*1024*1024) /* 物理内存可用于分页的总容量 */ #define PAGING_PAGES (PAGING_MEMORY>>12) /* 物理内存可用于分页的页数量 */ #define MAP_NR(addr) (addr>>12) /* 物理地址 addr 在物理内存页的第几页(从 0 开始计数) */ #define USED 1 #define UNUSED 0 unsigned long *pg_dir; /* 页目录表起始地址 */ static long HIGH_MEMORY =0; /* 全局变量,存放实际物理内存最高端地址。 */ static unsigned char mem_map[PAGING_PAGES] = {0,}; unsigned long get_free_page(void); int create_page_table(unsigned long addr); void invalidate(void) { __asm__("movl %%eax, %%cr3"::"a"(pg_dir)); } /* 主内存初始化 */ void mem_init(unsigned long start_mem, unsigned long end_mem) { int i; unsigned long mem_size; /* 主内存容量大小 */ pg_dir = PAGE_DIR_ADDR; /* PAGE_DIR_ADDR = 0x7000 */ HIGH_MEMORY = end_mem; /* 将 64M 物理内存页初始化为 1(USED) */ for (i=0 ; i<PAGING_PAGES ; i++) mem_map[i] = USED; i = MAP_NR(start_mem); /* 主内存起始地址在内存页的第几页(4KB为一页) */ mem_size = end_mem - start_mem; mem_size >>= 12; /* 主内存所拥有的内存页数量 */ /* 主内存页初始化为未使用 */ while (mem_size-- > 0) mem_map[i++] = UNUSED; } void copy_page(unsigned long from, unsigned long to) { int i; unsigned long *p = (unsigned long *)from; unsigned long *q = (unsigned long *)to; for(i=0; i<PAGE_SIZE/4; i++) *(q++) = *(p++); } /* 缺页处理,临时使用,并不完整,有待完善 */ void do_no_page(unsigned long addr) { unsigned long * table; unsigned long * page; unsigned long phys_addr; table = (unsigned long *)((unsigned long)pg_dir + ((addr>>20)&0xFFC)); while(!((*table) & 1)) { create_page_table(addr); table = (unsigned long *)((unsigned long)pg_dir + ((addr>>20)&0xFFC)); } page = (unsigned long *)(((*table)&0xFFFFF000) + ((addr>>10)&0xFFC)); if(addr < 64*1024*1024) *page = (addr & 0xFFFFF000) | 7; else { phys_addr = get_free_page(); if(phys_addr == 0) return; *page = phys_addr | 7; } invalidate(); } /* 写保护处理 */ void do_wp_page(unsigned long addr) { unsigned long * table; unsigned long * page; unsigned long old_page; unsigned long new_page; table = (unsigned long *)((unsigned long)pg_dir + ((addr>>20)&0xFFC)); page = (unsigned long *)(((*table)&0xFFFFF000) + ((addr>>10)&0xFFC)); old_page = (*page)&0xFFFFF000; if(mem_map[MAP_NR(old_page)] == 1) *page |= 2; else { if(!(new_page=get_free_page())) return; mem_map[MAP_NR(old_page)]--; copy_page(old_page, new_page); *page = new_page | 7; } invalidate(); } void do_intr_page(long *eip, unsigned long error_code) { unsigned long addr; __asm__ ( \ "movl %%cr2, %%eax\n\t" \ "sti" \ :"=a"(addr)); if((error_code & 0x1) == 0) do_no_page(addr); else /* (error_code & 0x1) != 0 */ do_wp_page(addr); } /* 获取空闲页面,返回物理地址,如果没有空闲页面,就返回0. */ unsigned long get_free_page(void) { long i,j; unsigned long * p; for (i=0 ; i<PAGING_PAGES ; i++) { if(mem_map[i] == 0) { if((i & 0x3FF) == 0x3FD) { mem_map[i] = 1; j = create_page_table((unsigned long)((i+2)<<12)); mem_map[i] = 0; if(j == -1) return 0; } p = (unsigned long *)(i << 12); for(j=0; j<(PAGE_SIZE/4); j++) *(p++) = 0; mem_map[i] = 1; return (unsigned long)(i<<12); } } return 0; } /* 创建页表,返回0表示已存在,返回1表示创建成功,返回-1表示创建失败 */ int create_page_table(unsigned long addr) { unsigned long * table; unsigned long page; table = (unsigned long *)((unsigned long)pg_dir + ((addr>>20)&0xFFC)); if((*table) & 1) return 0; page = get_free_page(); if(page == 0) return -1; page |= 7; *table = page; invalidate(); return 1; } /* 共享页面 */ void share_page(unsigned long from, unsigned long to) { unsigned long * from_table; unsigned long * from_page; unsigned long * to_table; unsigned long * to_page; unsigned long page; from_table = (unsigned long *)((unsigned long)pg_dir + ((from>>20)&0xFFC)); while(!((*from_table) & 1)) { do_no_page(from); from_table = (unsigned long *)((unsigned long)pg_dir + ((from>>20)&0xFFC)); } from_page = (unsigned long*)(((*from_table)&0xFFFFF000) + ((from>>10)&0xFFC)); while(!((*from_page) & 1)) { do_no_page(from); from_page = (unsigned long *)(((*from_table)&0xFFFFF000) + ((from>>10)&0xFFC)); } to_table = (unsigned long *)((unsigned long)pg_dir + ((to>>20)&0xFFC)); while(!((*to_table) & 1)) { create_page_table(to); to_table = (unsigned long *)((unsigned long)pg_dir + ((to>>20)&0xFFC)); } to_page = (unsigned long *)(((*to_table)&0xFFFFF000) + ((to>>10)&0xFFC)); page = *from_page; mem_map[MAP_NR(page)]++; page &= ~2; *to_page = page; if(from >= 64*1024*1024) *from_page = page; invalidate(); } /* 共享多个物理页面 */ int share_multi_pages(unsigned long from, unsigned long to, long amount) { if((from&0xFFF) || (to&0xFFF)) return -1; while(amount--) { share_page(from, to); from += 0x1000; to += 0x1000; } return 1; }
Cassidy/mks
include/kernel/messaging.h
<gh_stars>1-10 /********************************************* * File name: messaging.h * Author: Cassidy * Time-stamp: <2011-05-15 01:23:56> ********************************************* */ #ifndef _MESSAGING_H #define _MESSAGING_H #define MSG_ANY -1 #define MSG_HARDWARE -2 #define NR_MSG_HARDWARE 1024 /* 硬件中断消息数量 */ /* 消息结构体 */ struct msg_struct { long src; /* 消息的源进程 */ long dest; /* 消息的目的进程 */ long msg; /* 短消息内容或是长消息指针 */ struct msg_struct * next; }; #endif
Cassidy/mks
kernel/interrupt.c
<reponame>Cassidy/mks /********************************************* * File name: interrupt.c * Author: Cassidy * Time-stamp: <2011-05-29 04:32:03> ********************************************* */ #include <kernel/kernel.h> #include <kernel/interrupt.h> #include <kernel/head.h> #include <asm/system.h> /* set_trap_gate set_system_gate set_intr_gate */ #include <asm/io.h> /* outb_p inb_p */ #define INTR_NUM 255 /* 定义两个同义的函数指针,指向返回类型是 void,参数也是 void 的函数 */ typedef void (*intr_addr_t)(void); typedef void (*intr_proc_t)(void); extern void do_intr_clock(long *, long, long); /* kernel/time.c */ extern void do_intr_page(long *, unsigned long); /* kernel/memory.c */ extern void do_intr_keyboard(void); /* driver/character/keyboard.c */ struct desc_struct *idt; /* 定义指向中断描述符表的指针 */ intr_addr_t intr_enter[20] = { &intr0, &intr1, &intr2, &intr3, &intr4, &intr5, &intr6, &intr7, &intr8, &intr9, &intr10, &intr11, &intr12, &intr13, &intr14, &intr15, &intr16, &intr17, &intr18, &intr19 }; intr_addr_t hwintr_enter[16] = { &hwintr0, &hwintr1, &hwintr2, &hwintr3, &hwintr4, &hwintr5, &hwintr6, &hwintr7, &hwintr8, &hwintr9, &hwintr10, &hwintr11, &hwintr12, &hwintr13, &hwintr14, &hwintr15 }; intr_addr_t intr_reserv_enter = &intr_reserved; intr_addr_t intr_msg_enter = &intr_msg; intr_addr_t intr_kercall_enter = &intr_kercall; intr_proc_t intr_table[INTR_NUM]; /* 中断处理函数表 */ void do_intr_parallel(void) { outb(0x20, 0x20); } void do_intr_kercall(void) { printk("kernel call"); } void do_intr_reserved(void) { printk("intr_reserved"); } void do_intr_debug1(void) { printk("intr_occur"); } void do_intr_debug2(long esp, long error_code) { printbin((unsigned long)error_code); println(); } void do_intr_0(void){printk("intr_occur 0");} void do_intr_1(void){printk("intr_occur 1");} void do_intr_2(void){printk("intr_occur 2");} void do_intr_3(void){printk("intr_occur 3");} void do_intr_4(void){printk("intr_occur 4");} void do_intr_5(void){printk("intr_occur 5");} void do_intr_6(void){printk("intr_occur 6");} void do_intr_7(void){printk("intr_occur 7");} void do_intr_8(void){printk("intr_occur 8");} void do_intr_9(void){printk("intr_occur 9");} void do_intr_10(void){printk("intr_occur 10");} void do_intr_11(void){printk("intr_occur 11");} void do_intr_12(void){printk("intr_occur 12");} void do_intr_13(void){printk("intr_occur 13");} void do_intr_14(void){printk("intr_occur 14");} void do_intr_15(void){printk("intr_occur 15");} void do_intr_16(void){printk("intr_occur 16");} void do_intr_17(void){printk("intr_occur 17");} void do_intr_18(void){printk("intr_occur 18");} void do_intr_19(void){printk("intr_occur 19");} void do_intr_20(void){printk("intr_occur 20");} void do_intr_21(void){printk("intr_occur 21");} void do_intr_22(void){printk("intr_occur 22");} void do_intr_23(void){printk("intr_occur 23");} void do_intr_24(void){printk("intr_occur 24");} void do_intr_25(void){printk("intr_occur 25");} void do_intr_26(void){printk("intr_occur 26");} void do_intr_27(void){printk("intr_occur 27");} void do_intr_28(void){printk("intr_occur 28");} void do_intr_29(void){printk("intr_occur 29");} void do_intr_30(void){printk("intr_occur 30");} void do_intr_31(void){printk("intr_occur 31");} void do_intr_32(void){printk("intr_occur 32");} void do_intr_33(void){printk("intr_occur 33");} void do_intr_34(void){printk("intr_occur 34");} void do_intr_35(void){printk("intr_occur 35");} void do_intr_36(void){printk("intr_occur 36");} void do_intr_37(void){printk("intr_occur 37");} void do_intr_38(void){printk("intr_occur 38");} void do_intr_39(void){printk("intr_occur 39");} void do_intr_40(void){printk("intr_occur 40");} void do_intr_41(void){printk("intr_occur 41");} void do_intr_42(void){printk("intr_occur 42");} void do_intr_43(void){printk("intr_occur 43");} void do_intr_44(void){printk("intr_occur 44");} void do_intr_45(void){printk("intr_occur 45");} void do_intr_46(void){printk("intr_occur 46");} void do_intr_47(void){printk("intr_occur 47");} void do_intr_48(void){printk("intr_occur 48");} void do_intr_49(void){printk("intr_occur 49");} void do_intr_50(void){printk("intr_occur 50");} void do_intr_51(void){printk("intr_occur 51");} void do_intr_52(void){printk("intr_occur 52");} void do_intr_53(void){printk("intr_occur 53");} void do_intr_54(void){printk("intr_occur 54");} void do_intr_55(void){printk("intr_occur 55");} void do_intr_56(void){printk("intr_occur 56");} void do_intr_57(void){printk("intr_occur 57");} void do_intr_58(void){printk("intr_occur 58");} void do_intr_59(void){printk("intr_occur 59");} /* 中断初始化 */ void intr_init() { int i; idt = IDT_ADDR; /* IDT_ADDR = 0x6000 */ /* 初始化所有中断处理函数为保留的 */ for(i=0; i<255; i++) intr_table[i] = &do_intr_reserved; /* 设置特定的中断处理函数 */ intr_table[13] = &do_intr_debug2; intr_table[14] = &do_intr_page; intr_table[32] = &do_intr_clock; intr_table[33] = &do_intr_keyboard; intr_table[39] = &do_intr_parallel; intr_table[0x88] = &do_intr_kercall; intr_table[10] = &do_intr_10; intr_table[11] = &do_intr_11; intr_table[12] = &do_intr_12; /* intr_table[13] = &do_intr_debug2; */ /* intr_table[14] = &do_intr_page; */ intr_table[15] = &do_intr_15; intr_table[16] = &do_intr_16; intr_table[17] = &do_intr_17; intr_table[18] = &do_intr_18; intr_table[19] = &do_intr_19; intr_table[20] = &do_intr_20; intr_table[21] = &do_intr_21; intr_table[22] = &do_intr_22; intr_table[23] = &do_intr_23; intr_table[24] = &do_intr_24; intr_table[25] = &do_intr_25; intr_table[26] = &do_intr_26; intr_table[27] = &do_intr_27; intr_table[28] = &do_intr_28; intr_table[29] = &do_intr_29; intr_table[30] = &do_intr_30; intr_table[31] = &do_intr_31; /* intr_table[32] = &do_intr_clock; */ /* intr_table[33] = &do_intr_keyboard; */ intr_table[34] = &do_intr_34; intr_table[35] = &do_intr_35; intr_table[36] = &do_intr_36; intr_table[37] = &do_intr_37; intr_table[38] = &do_intr_38; /* intr_table[39] = &do_intr_parallel; */ intr_table[40] = &do_intr_40; intr_table[41] = &do_intr_41; intr_table[42] = &do_intr_42; intr_table[43] = &do_intr_43; intr_table[44] = &do_intr_44; intr_table[45] = &do_intr_45; intr_table[46] = &do_intr_46; intr_table[47] = &do_intr_47; intr_table[48] = &do_intr_48; intr_table[49] = &do_intr_49; intr_table[50] = &do_intr_50; intr_table[51] = &do_intr_51; intr_table[52] = &do_intr_52; intr_table[53] = &do_intr_53; intr_table[54] = &do_intr_54; intr_table[55] = &do_intr_55; intr_table[56] = &do_intr_56; intr_table[57] = &do_intr_57; intr_table[58] = &do_intr_58; intr_table[59] = &do_intr_59; /* 设置中断描述符表 */ for(i=0; i<=2; i++) set_trap_gate(i, intr_enter[i]); for(i=3; i<=5; i++) set_system_gate(i, intr_enter[i]); for(i=6; i<=19; i++) set_trap_gate(i, intr_enter[i]); for(i=20; i<=31; i++) set_trap_gate(i, intr_reserv_enter); /* 陷阱门,不复位 IF 标志 */ for(i=32; i<=47; i++) set_trap_gate(i, hwintr_enter[i-32]); for(i=48; i<=255; i++) set_trap_gate(i, intr_reserv_enter); set_intr_gate(14, intr_enter[14]); /* 页面错误,中断门 */ set_system_gate(0x80, intr_msg_enter); /* 消息中断 */ set_system_gate(0x88, intr_kercall_enter); /* 内核调用中断 */ /* 宏函数(include/asm/io.h): outb_p(value, port) inb_p(port) */ outb_p(inb_p(0x21) & 0xF9, 0x21); /* 开启键盘中断(IRQ1)和接连从芯片(IRQ2) */ }
Cassidy/mks
kernel/printk.c
/********************************************* * File name: printk.c * Author: Cassidy * Time-stamp: <2011-05-10 21:30:23> ********************************************* */ #include <asm/io.h> /* outb_p */ #define ORIG 0xb8000 /* 显存首地址 */ static unsigned long video_num_columns = 80; /* 屏幕文本列数 */ static unsigned long pos; /* 显示内存一位置 */ static unsigned long x,y; /* 当前光标位置 */ static unsigned char attr = 0x07; /* 字符属性(黑底白字) */ static inline void update_cursor(void); static inline void write_char(char); void con_init(void); /* 显示初始化 */ int printk(const char *); /* 输出字符串 */ int prints(const char *); /* 输出字符串 */ void printa(const long a); /* 输出长整型变量 */ void printbin(const unsigned long); /* 输出二进制数 */ void printchar(unsigned char c); /* 显示字符 */ void printhex(unsigned char c); /* 显示十六进制数 */ /* 显示初始化 */ void con_init() { x = 0; y = 0; char * ph = ORIG; /* 显存开始位置 */ char * pe = ORIG + 4000; /* 显存结束位置 */ /* 清屏 */ while(ph < pe) { *ph++ = 32; /* 显示空字符 */ *ph++ = attr; /* 黑底白字 */ } printk(" MKS -- Micro Kernel for Study "); update_cursor(); } /* 输出一字符,光标位置进一 */ static inline void write_char(char ch) { pos = ORIG + video_num_columns * 2 * y + x * 2; *((char *)pos) = ch; *((char *)(pos+1)) = attr; x++; if(x >= 80) { y += x / 80; x = x % 80; } if(y >= 25) { con_init(); y = y % 25; } } /* update_cursor: 设置光标跟随,更新光标位置 */ static inline void update_cursor(void) { pos = ORIG + (video_num_columns * y + x) * 2; outb_p(0xE, 0x3D4); outb_p((pos>>8) & 0xFF, 0x3D5); outb_p(0xF, 0x3D4); outb_p(pos & 0xFF, 0x3D5); } /* 光标移至下一行开头 */ void println(void) { char * ph = ORIG + video_num_columns * 2 * y + x * 2; //原光标位置 char * pe; x = 0; y++; if(y < 25) pe = ORIG + video_num_columns * 2 * (y + 1); else { /* 先清除屏幕的第一行 */ char * ph1 = ORIG; char * pe1 = ORIG + video_num_columns * 2; while(ph1 < pe1) { *ph1++ = 32; *ph1++ = attr; } pe = ORIG + video_num_columns * 2 * y; y = 0; } while(ph < pe) { *ph++ = 32; *ph++ = attr; } } /* 输出字符串,返回输出字符个数 */ int prints(const char *fmt) { int i; char * ps = fmt; for(i=0; *ps!='\0'; i++) { write_char(*ps); ps++; } return i; } /* 将十进制数每位转为字符输出 */ static inline void print_charina(unsigned long a) { unsigned long b, c; if(a == 0) return; b = a / 10; c = b * 10; c = a - c; print_charina(b); c = c + 48; write_char((char)c); } /* 输出长整型娈量 */ void printa(const long a) { unsigned long b = (unsigned long)a; unsigned long c = b >> 31; if(c == 1) { write_char('-'); b = ~(b-1); } c = b & 0x7FFFFFFF; if(c == 0) write_char(48); else print_charina(c); } /* 输出二进制数 */ void printbin(const unsigned long el) { int i; unsigned long ef = el; for(i=32; i>0; i--) { if(ef & 0x80000000) write_char(49); else write_char(48); ef = ef << 1; } } /* printhex: 输出十六进制数 */ void printhex(unsigned char c) { int i; unsigned char tmp; write_char(48); /* '0' */ write_char(120); /* 'x' */ for (i = 0; i < 2; ++i) { c = (c << 4) | (c >> 4); /* 右旋 4 位 */ tmp = c & 0x0F; if (tmp > 9) tmp = tmp - 10 + 'A'; else if (0 <= tmp && tmp <= 9) tmp = tmp + '0'; else /* error */ printk("error"); write_char(tmp); } } /* printchar: 打印字符,供其他程序调用 */ void printchar(unsigned char c) { pos = ORIG + (video_num_columns * y + x) * 2; (*(char *)pos) = c; (*(char *)(pos + 1)) = attr; ++x; if (x >= 80) { x = 0; ++y; } if (y >= 25) { y = 1; x = 0; } } /* 内核输出函数,暂时使用prints(输出字符串) */ int printk(const char *fmt) { int a; a = prints(fmt); println(); return a; }
Cassidy/mks
init_proc/init.c
<filename>init_proc/init.c /********************************************* * File name: init.c * Author: Cassidy * Time-stamp: <2011-06-10 14:53:28> ********************************************* */ #include <unistd.h> void init_proc(void) { for(;;) ; }
Cassidy/mks
include/kernel/interrupt.h
/********************************************* * File name: interrupt.h * Author: Cassidy * Time-stamp: <2011-04-18 23:39:49> ********************************************* */ #ifndef _INTERRUPT_H #define _INTERRUPT_H /* 下面的函数在 kernel/asm.s中定义 */ extern void intr0(); extern void intr1(); extern void intr2(); extern void intr3(); extern void intr4(); extern void intr5(); extern void intr6(); extern void intr7(); extern void intr8(); extern void intr9(); extern void intr10(); extern void intr11(); extern void intr12(); extern void intr13(); extern void intr14(); extern void intr15(); extern void intr16(); extern void intr17(); extern void intr18(); extern void intr19(); extern void hwintr0(); extern void hwintr1(); extern void hwintr2(); extern void hwintr3(); extern void hwintr4(); extern void hwintr5(); extern void hwintr6(); extern void hwintr7(); extern void hwintr8(); extern void hwintr9(); extern void hwintr10(); extern void hwintr11(); extern void hwintr12(); extern void hwintr13(); extern void hwintr14(); extern void hwintr15(); extern void hwintr16(); extern void intr_msg(); extern void intr_kercall(); extern void intr_reserved(); #endif
Cassidy/mks
include/asm/io.h
<filename>include/asm/io.h /********************************************* * File name: io.h * Author: Cassidy * Time-stamp: <2011-04-17 20:16:39> ********************************************* */ #ifndef _IO_H #define _IO_H #define outb(value, port) \ __asm__("outb %%al, %%dx"::"a"(value), "d"(port)) #define inb(port) ({\ unsigned char _v;\ __asm__ volatile("inb %%dx, %%al":"=a"(_v):"d"(port));\ _v;\ }) #define outb_p(value, port) \ __asm__("outb %%al, %%dx\n"\ "\tjmp 1f\n"\ "1:\tjmp 1f\n"\ "1:"::"a"(value), "d"(port)) #define inb_p(port) ({\ unsigned char _v;\ __asm__ volatile("inb %%dx, %%al\n"\ "\tjmp 1f\n"\ "1:\tjmp 1f\n"\ "1:":"=a"(_v):"d"(port));\ _v;\ }) #endif
Cassidy/mks
include/kernel/head.h
/********************************************* * File name: head.h * Author: Cassidy * Time-stamp: <2011-04-24 06:20:36> ********************************************* */ #ifndef _HEAD_H #define _HEAD_H /* 描述符结构体 */ struct desc_struct { unsigned long a, b; }; extern struct desc_struct *idt; /* kernel/interrupt.c */ extern struct desc_struct *gdt; /* kernel/proc.c */ extern unsigned long *pg_dir; /* kernel/memory.c */ #endif
OzanEm/Chain-Block-Cipher-implementation-
fscrypt.h
#include "openssl/blowfish.h" #include <cstdio> #include <cstdlib> #include <iostream> #include <cstring> #include <vector> using namespace std; void *fs_encrypt(void *plaintext, int bufsize, char *keystr, int *resultlen); void *fs_decrypt(void *ciphertext, int bufsize, char *keystr, int *resultlen); const int BLOCKSIZE = 8;
JingtingChen/DAMessage
Example/Pods/Headers/Public/DAMessage/UIColor+JSQMessages.h
<filename>Example/Pods/Headers/Public/DAMessage/UIColor+JSQMessages.h<gh_stars>0 // // Created by <NAME> // http://www.jessesquires.com // // // Documentation // http://cocoadocs.org/docsets/JSQMessagesViewController // // // GitHub // https://github.com/jessesquires/JSQMessagesViewController // // // License // Copyright (c) 2014 <NAME> // Released under an MIT license: http://opensource.org/licenses/MIT // #import <UIKit/UIKit.h> @interface UIColor (JSQMessages) #pragma mark - Message bubble colors /** * @return A color object containing HSB values similar to the iOS 7 messages app green bubble color. */ + (UIColor *)jsq_messageBubbleGreenColor; /** * @return A color object containing HSB values similar to the iOS 7 messages app blue bubble color. */ + (UIColor *)jsq_messageBubbleBlueColor; /** * @return A color object containing HSB values similar to the iOS 7 red color. */ + (UIColor *)jsq_messageBubbleRedColor; /** * @return A color object containing HSB values similar to the iOS 7 messages app light gray bubble color. */ + (UIColor *)jsq_messageBubbleLightGrayColor; #pragma mark - Utilities /** * Creates and returns a new color object whose brightness component is decreased by the given value, using the initial color values of the receiver. * * @param value A floating point value describing the amount by which to decrease the brightness of the receiver. * * @return A new color object whose brightness is decreased by the given values. The other color values remain the same as the receiver. */ - (UIColor *)jsq_colorByDarkeningColorWithValue:(CGFloat)value; @end
JingtingChen/DAMessage
Example/Pods/Target Support Files/Pods-DAMessage_Tests/Pods-DAMessage_Tests-environment.h
<reponame>JingtingChen/DAMessage // To check if a library is compiled with CocoaPods you // can use the `COCOAPODS` macro definition which is // defined in the xcconfigs so it is available in // headers also when they are imported in the client // project. // DAMessage #define COCOAPODS_POD_AVAILABLE_DAMessage #define COCOAPODS_VERSION_MAJOR_DAMessage 0 #define COCOAPODS_VERSION_MINOR_DAMessage 1 #define COCOAPODS_VERSION_PATCH_DAMessage 0 // M13BadgeView #define COCOAPODS_POD_AVAILABLE_M13BadgeView #define COCOAPODS_VERSION_MAJOR_M13BadgeView 1 #define COCOAPODS_VERSION_MINOR_M13BadgeView 0 #define COCOAPODS_VERSION_PATCH_M13BadgeView 4
JingtingChen/DAMessage
Example/Pods/Target Support Files/Pods-DAMessage_Tests-M13BadgeView/Pods-DAMessage_Tests-M13BadgeView-umbrella.h
<filename>Example/Pods/Target Support Files/Pods-DAMessage_Tests-M13BadgeView/Pods-DAMessage_Tests-M13BadgeView-umbrella.h #import <UIKit/UIKit.h> #import "M13BadgeView.h" FOUNDATION_EXPORT double M13BadgeViewVersionNumber; FOUNDATION_EXPORT const unsigned char M13BadgeViewVersionString[];
JingtingChen/DAMessage
Example/Pods/Target Support Files/Pods-DAMessage_Tests/Pods-DAMessage_Tests-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_DAMessage_TestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_DAMessage_TestsVersionString[];
JingtingChen/DAMessage
Example/Pods/Headers/Public/DAMessage/JSQMessagesAvatarImageFactory.h
<reponame>JingtingChen/DAMessage<filename>Example/Pods/Headers/Public/DAMessage/JSQMessagesAvatarImageFactory.h // // Created by <NAME> // http://www.jessesquires.com // // // Documentation // http://cocoadocs.org/docsets/JSQMessagesViewController // // // GitHub // https://github.com/jessesquires/JSQMessagesViewController // // // License // Copyright (c) 2014 <NAME> // Released under an MIT license: http://opensource.org/licenses/MIT // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "JSQMessagesAvatarImage.h" /** * `JSQMessagesAvatarImageFactory` is a factory that provides a means for creating and styling * `JSQMessagesAvatarImage` objects to be displayed in a `JSQMessagesCollectionViewCell` of a `JSQMessagesCollectionView`. */ @interface JSQMessagesAvatarImageFactory : NSObject /** * Creates and returns a `JSQMessagesAvatarImage` object with the specified placeholderImage that is * cropped to a circle of the given diameter. * * @param placeholderImage An image object that represents a placeholder avatar image. This value must not be `nil`. * @param diameter An integer value specifying the diameter size of the avatar in points. This value must be greater than `0`. * * @return An initialized `JSQMessagesAvatarImage` object if created successfully, `nil` otherwise. */ + (JSQMessagesAvatarImage *)avatarImageWithPlaceholder:(UIImage *)placeholderImage diameter:(NSUInteger)diameter; /** * Creates and returns a `JSQMessagesAvatarImage` object with the specified image that is * cropped to a circle of the given diameter and used for the `avatarImage` and `avatarPlaceholderImage` properties * of the returned `JSQMessagesAvatarImage` object. This image is then copied and has a transparent black mask applied to it, * which is used for the `avatarHighlightedImage` property of the returned `JSQMessagesAvatarImage` object. * * @param image An image object that represents an avatar image. This value must not be `nil`. * @param diameter An integer value specifying the diameter size of the avatar in points. This value must be greater than `0`. * * @return An initialized `JSQMessagesAvatarImage` object if created successfully, `nil` otherwise. */ + (JSQMessagesAvatarImage *)avatarImageWithImage:(UIImage *)image diameter:(NSUInteger)diameter; /** * Returns a copy of the specified image that is cropped to a circle with the given diameter. * * @param image The image to crop. This value must not be `nil`. * @param diameter An integer value specifying the diameter size of the image in points. This value must be greater than `0`. * * @return A new image object if successful, `nil` otherwise. */ + (UIImage *)circularAvatarImage:(UIImage *)image withDiameter:(NSUInteger)diameter; /** * Returns a copy of the specified image that is cropped to a circle with the given diameter. * Additionally, a transparent overlay is applied to the image to represent a pressed or highlighted state. * * @param image The image to crop. This value must not be `nil`. * @param diameter An integer value specifying the diameter size of the image in points. This value must be greater than `0`. * * @return A new image object if successful, `nil` otherwise. */ + (UIImage *)circularAvatarHighlightedImage:(UIImage *)image withDiameter:(NSUInteger)diameter; /** * Creates and returns a `JSQMessagesAvatarImage` object with a circular shape that displays the specified userInitials * with the given backgroundColor, textColor, font, and diameter. * * @param userInitials The user initials to display in the avatar image. This value must not be `nil`. * @param backgroundColor The background color of the avatar. This value must not be `nil`. * @param textColor The color of the text of the userInitials. This value must not be `nil`. * @param font The font applied to userInitials. This value must not be `nil`. * @param diameter The diameter of the avatar image. This value must be greater than `0`. * * @return An initialized `JSQMessagesAvatarImage` object if created successfully, `nil` otherwise. * * @discussion This method does not attempt to detect or correct incompatible parameters. * That is to say, you are responsible for providing a font size and diameter that make sense. * For example, a font size of `14.0f` and a diameter of `34.0f` will result in an avatar similar to Messages in iOS 7. * However, a font size `30.0f` and diameter of `10.0f` will not produce a desirable image. * Further, this method does not check the length of userInitials. It is recommended that you pass a string of length `2` or `3`. */ + (JSQMessagesAvatarImage *)avatarImageWithUserInitials:(NSString *)userInitials backgroundColor:(UIColor *)backgroundColor textColor:(UIColor *)textColor font:(UIFont *)font diameter:(NSUInteger)diameter; @end
JingtingChen/DAMessage
Example/Pods/Headers/Public/DAMessage/JSQMessagesMediaViewBubbleImageMasker.h
<filename>Example/Pods/Headers/Public/DAMessage/JSQMessagesMediaViewBubbleImageMasker.h // // Created by <NAME> // http://www.jessesquires.com // // // Documentation // http://cocoadocs.org/docsets/JSQMessagesViewController // // // GitHub // https://github.com/jessesquires/JSQMessagesViewController // // // License // Copyright (c) 2014 <NAME> // Released under an MIT license: http://opensource.org/licenses/MIT // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @class JSQMessagesBubbleImageFactory; /** * An instance of `JSQMessagesMediaViewBubbleImageMasker` is an object that masks * media views for a `JSQMessageMediaData` object. Given a view, it will mask the view * with a bubble image for an outgoing or incoming media view. * * @see JSQMessageMediaData. * @see JSQMessagesBubbleImageFactory. * @see JSQMessagesBubbleImage. */ @interface JSQMessagesMediaViewBubbleImageMasker : NSObject /** * Returns the bubble image factory that the masker uses to mask media views. */ @property (strong, nonatomic, readonly) JSQMessagesBubbleImageFactory *bubbleImageFactory; /** * Creates and returns a new instance of `JSQMessagesMediaViewBubbleImageMasker` * that uses a default instance of `JSQMessagesBubbleImageFactory`. The masker uses the `JSQMessagesBubbleImage` * objects returned by the factory to mask media views. * * @return An initialized `JSQMessagesMediaViewBubbleImageMasker` object if created successfully, `nil` otherwise. * * @see JSQMessagesBubbleImageFactory. * @see JSQMessagesBubbleImage. */ - (instancetype)init; /** * Creates and returns a new instance of `JSQMessagesMediaViewBubbleImageMasker` * having the specified bubbleImageFactory. The masker uses the `JSQMessagesBubbleImage` * objects returned by the factory to mask media views. * * @param bubbleImageFactory An initialized `JSQMessagesBubbleImageFactory` object to use for masking media views. This value must not be `nil`. * * @return An initialized `JSQMessagesMediaViewBubbleImageMasker` object if created successfully, `nil` otherwise. * * @see JSQMessagesBubbleImageFactory. * @see JSQMessagesBubbleImage. */ - (instancetype)initWithBubbleImageFactory:(JSQMessagesBubbleImageFactory *)bubbleImageFactory; /** * Applies an outgoing bubble image mask to the specified mediaView. * * @param mediaView The media view to mask. */ - (void)applyOutgoingBubbleImageMaskToMediaView:(UIView *)mediaView; /** * Applies an incoming bubble image mask to the specified mediaView. * * @param mediaView The media view to mask. */ - (void)applyIncomingBubbleImageMaskToMediaView:(UIView *)mediaView; /** * A convenience method for applying a bubble image mask to the specified mediaView. * This method uses the default instance of `JSQMessagesBubbleImageFactory`. * * @param mediaView The media view to mask. * @param isOutgoing A boolean value specifiying whether or not the mask should be for an outgoing or incoming view. * Specify `YES` for outgoing and `NO` for incoming. */ + (void)applyBubbleImageMaskToMediaView:(UIView *)mediaView isOutgoing:(BOOL)isOutgoing; @end
JingtingChen/DAMessage
Example/Pods/Headers/Public/DAMessage/DAMessageIndicator.h
<reponame>JingtingChen/DAMessage // // DAMessageIndicator.h // Pods // // Created by 陈婧婷 on 15/7/16. // // #import <UIKit/UIKit.h> #import "M13BadgeView.h" @interface DAMessageIndicator : UIView @property (nonatomic, strong) UIActivityIndicatorView *spinner; @property (nonatomic, strong) UIImageView *failureImage; @property (nonatomic, strong) M13BadgeView *badgeView; -(void)showMessageSending; -(void)stopMessageSending; -(void)showMessageFailure; -(void)showMessageSuccess:(int)tag; @end
pupapaik/Mayastor
spdk-sys/logwrapper.h
#include <stddef.h> #include <stdarg.h> #include <spdk/log.h> typedef void maya_logger(int level, const char *file, const int line, const char *func, const char *buf, const int len); // pointer is set from within rust to point to our logging trampoline maya_logger *logfn = NULL;
amondrag98/mi-primer-repo
presentacion.c
#include<studio.h> //studio -> standard Input/output int main(){ printf("Hola Mundo, mi nombre es:"); printf("<NAME>"); return 0; }
fukuroder/Raspberry-Pi-synthesizer-test
blit_saw_oscillator.h
/* * blit_saw_oscillator.h * * Copyright (c) 2014, fukuroda (https://github.com/fukuroder) * Released under the MIT license */ #pragma once #include<array> // class blit_saw_oscillator_note { public: // blit_saw_oscillator_note(); // ADSR enum ADSR { // Off, // On, }; // ADSR envelope; // double t; // double value; // int n; // double dt; // unsigned char note_no; // double velocity; }; // class blit_saw_oscillator { public: // constructor blit_saw_oscillator(double leak, double srate); // void trigger(unsigned char note_no, unsigned char velocity); // void release(unsigned char note_no); // double process(); protected: // static const int _note_no_center = 69; // double _Leak; // double srate; // std::array<double, (1<<10)+1> _sinTable; // std::array<blit_saw_oscillator_note, 4> _notes; // double linear_interpolated_sin( double t ); // double bandlimited_impulse( double t, int n ); };
nikhilc149/e-utran-features-bug-fixes
cp/li_config.h
/* * Copyright (c) 2017 Intel Corporation * Copyright (c) 2020 T-Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __LI_CONFIG_H_ #define __LI_CONFIG_H_ #include "pfcp_enum.h" #include "gw_adapter.h" #include "pfcp_util.h" #define ADD_LI_ENTRY 1 #define UPDATE_LI_ENTRY 2 #define DELETE_LI_ENTRY 3 extern struct rte_hash *li_info_by_imsi_hash; extern struct rte_hash *li_id_by_imsi_hash; /** * @brief : Delete LI entry using id * @param : uiId[], array contains li entries to delete from hash and stop li * @param : uiCntr, number of entries in array * @return : Returns 0 in case of success , -1 otherwise */ uint8_t del_li_entry(uint64_t *uiId, uint16_t uiCntr); /** * @brief : Fill LI config values * @param : li_config_t, array of structure from which li_config is to be filled * @param : uiCntr, number of entries in array * @return : Returns 0 in case of success , -1 otherwise */ int8_t fillup_li_df_hash(struct li_df_config_t *li_df_config, uint16_t uiCntr); /** * @brief : Retrive LI UE Database As Per IMSI * @param : uiImsi, key for search * @param : li_config_t, structure to store retrived li_config * @return : Returns 0 in case of success , -1 otherwise */ int get_li_config(uint64_t uiImsi, struct li_df_config_t **li_config); /** * @brief : add id in imsi hash * @param : uiId, key for search * @param : uiImsi, IMSI * @return : Returns 0 in case of success , -1 otherwise */ int8_t add_id_in_imsi_hash(uint64_t uiId, uint64_t uiImsi); /** * @brief : get id from imsi hash * @param : uiImsi, key for search imsi * @param : imsi_id_hash, structure for imsi id * @return : Returns 0 in case of success , -1 otherwise */ int get_id_using_imsi(uint64_t uiImsi, imsi_id_hash_t **imsi_id_hash); /** * @brief : fill li configuration in context * @param : ue_context, context of ue * @param : imsi_id_config, imsi to li id mapping * @return : Returns 0 in case of success , -1 otherwise */ int fill_li_config_in_context(ue_context *context, imsi_id_hash_t *imsi_id_config); #endif // __LI_CONFIG_H_
nikhilc149/e-utran-features-bug-fixes
dp/pipeline/epc_spns_dns.c
/* * Copyright (c) 2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include <sched.h> #include <inttypes.h> #include <sys/types.h> #include <sys/queue.h> #include <netinet/in.h> #include <setjmp.h> #include <stdarg.h> #include <ctype.h> #include <errno.h> #include <getopt.h> #include <rte_common.h> #include <rte_log.h> #include <rte_memory.h> #include <rte_memcpy.h> #include <rte_memzone.h> #include <rte_eal.h> #include <rte_per_lcore.h> #include <rte_launch.h> #include <rte_atomic.h> #include <rte_spinlock.h> #include <rte_cycles.h> #include <rte_prefetch.h> #include <rte_lcore.h> #include <rte_per_lcore.h> #include <rte_branch_prediction.h> #include <rte_interrupts.h> #include <rte_pci.h> #include <rte_random.h> #include <rte_debug.h> #include <rte_ether.h> #include <rte_ethdev.h> #include <rte_ring.h> #include <rte_mempool.h> #include <rte_mbuf.h> #include <rte_malloc.h> #include <rte_ip.h> #include <rte_udp.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdbool.h> #include <sponsdn.h> #include "up_main.h" #include "gw_adapter.h" #define NB_CORE_MSGBUF 10000 #define MAX_NAME_LEN 32 static struct rte_mempool *message_pool; extern struct rte_ring *epc_mct_spns_dns_rx; extern int clSystemLog; uint64_t num_dns_processed; void epc_spns_dns_init(void) { message_pool = rte_pktmbuf_pool_create("ms_msg_pool", NB_CORE_MSGBUF, 32, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id()); if (message_pool == NULL) rte_exit(EXIT_FAILURE, LOG_FORMAT"Create msg mempool failed\n", LOG_VALUE); } int push_dns_ring(struct rte_mbuf *pkts) { void *msg; int ret; if (epc_mct_spns_dns_rx == NULL) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"rte ring value is NULL\n", LOG_VALUE); return -1; } msg = (void *)rte_pktmbuf_clone(pkts, message_pool); if (msg == NULL) { clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"Error to get message buffer\n", LOG_VALUE); return -1; } ret = rte_ring_mp_enqueue(epc_mct_spns_dns_rx, (void *)msg); if (ret != 0) { clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"DNS ring: error enqueuing\n", LOG_VALUE); rte_pktmbuf_free(msg); return -1; } return 0; } void scan_dns_ring(void) { void *msg; int ret; int i; if (epc_mct_spns_dns_rx == NULL) return; ret = rte_ring_sc_dequeue(epc_mct_spns_dns_rx, &msg); if (ret == 0) { /* DNSTODO: IP header with options */ unsigned dns_payload_off = sizeof(struct ether_hdr) + sizeof(struct ipv4_hdr) + sizeof(struct udp_hdr); int addr4_cnt; struct in_addr addr4[100]; unsigned match_id; struct rte_mbuf *pkts = (struct rte_mbuf *)msg; epc_sponsdn_scan(rte_pktmbuf_mtod(pkts, char *) + dns_payload_off, rte_pktmbuf_data_len(pkts) - dns_payload_off, NULL, &match_id, addr4, &addr4_cnt, NULL, NULL, NULL); ++num_dns_processed; for (i = 0; i < addr4_cnt; ++i) { //struct msg_adc msg = { .ipv4 = addr4[i].s_addr, .rule_id = match_id }; clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"Adding a rule with IP: %s, rule id: %d\n", LOG_VALUE, inet_ntoa(addr4[i]), match_id); //adc_dns_entry_add(&msg); } rte_pktmbuf_free(msg); } }
nikhilc149/e-utran-features-bug-fixes
ulpc/df/include/TCPDataProcessor.h
<gh_stars>0 /* * Copyright (c) 2020 Sprint * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef __PCAP_DATA_PROCESSOR_H_ #define __PCAP_DATA_PROCESSOR_H_ #include "Common.h" #include "TCPListener.h" #define ERROR -1 class TCPListener; class DfListener : public ESocket::TCP::ListenerPrivate { public: /* * @brief : Constructor of class DdfListener */ DfListener(TCPListener &thread); /* * @brief : Destructor of class DdfListener */ ~DfListener(); /* * @brief : Library function of EPCTool */ Void onClose(); /* * @brief : Library function of EPCTool */ Void onError(); ESocket::TCP::TalkerPrivate *createSocket(ESocket::ThreadPrivate &thread); private: /* * @brief : Constructor of class DdfListener */ DfListener(); }; class TCPDataProcessor : public ESocket::TCP::TalkerPrivate { public: /* * @brief : Constructor of class TCPDataProcessor */ TCPDataProcessor(TCPListener &thread); /* * @brief : Destructor of class TCPDataProcessor */ virtual ~TCPDataProcessor(); /* * @brief : Function to process data received from DDF * @param : buffer, collects packet/information to be processed * @return : Returns void */ void processPacket(uint8_t *buffer); /* * @brief : Library function of EPCTool */ Void onConnect(); /* * @brief : Library function of EPCTool */ Void onReceive(); /* * @brief : Library function of EPCTool */ Void onClose(); /* * @brief : Library function of EPCTool */ Void onError(); /* * @brief : Function to send packet acknowledgement CP/DP * @param : buffer, collects packet/information to be processed * @return : Returns void */ Void sendAck(uint32_t seqNbr); private: /* * @brief : Constructor of class TCPDataProcessor */ TCPDataProcessor(); static uint32_t sequence_numb; }; #endif /* __PCAP_DATA_PROCESSOR_H_ */
nikhilc149/e-utran-features-bug-fixes
cp/gtpv2c_error_rsp.h
<reponame>nikhilc149/e-utran-features-bug-fixes /* * Copyright (c) 2019 Sprint * Copyright (c) 2020 T-Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _GTPV2C_ERROR_RSP_H_ #define _GTPV2C_ERROR_RSP_H_ #include "ue.h" #include "gtpv2c.h" #include "sm_struct.h" #include "gtpv2c_ie.h" #include "pfcp_util.h" #include "pfcp_session.h" #include "gtpv2c_set_ie.h" #include "pfcp_messages_encoder.h" #include "./gx_app/include/gx.h" #include "cp.h" extern struct rte_hash *bearer_by_fteid_hash; /** * @brief : Maintains data to be filled in error response */ typedef struct err_rsp_info_t { uint8_t cp_mode; uint32_t sender_teid; uint32_t teid; uint32_t seq; uint8_t ebi; uint8_t offending; uint8_t bearer_count; uint8_t bearer_id[MAX_BEARERS]; }err_rsp_info; /** * @brief : Performs clean up task * @param : ebi, bearer id * @param : teid, teid value * @param : imsi_val, imsi value * @param : imsi_len, imsi length * @param : seq, sequence * @param : msg, message info * @return : Returns nothing */ int8_t clean_up_while_error(uint8_t ebi, ue_context *context, uint32_t teid, uint64_t *imsi_val, uint32_t seq, msg_info *msg); /** * @brief : Performs clean up task after create bearer error response * @param : teid, teid value * @param : msg_type, type of message * @param : pdn, PDN structure * @return : Returns nothing */ int8_t clean_up_while_cbr_error(uint32_t teid, uint8_t msg_type, pdn_connection *pdn); /** * @brief : Set and send error response in case of processing create session request * @param : msg, holds information related to message caused error * @param : cause_value, cause type of error * @param : cause_source, cause source of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void cs_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Set and send error response in case of processing modify bearer request * @param : msg, holds information related to message caused error * @param : cause_value, cause type of error * @param : cause_source, cause source of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void mbr_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Set and send error response in case of processing delete session request * @param : msg, holds information related to message caused error * @param : cause_value, cause type of error * @param : cause_source, cause source of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void ds_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Gets information related to error and fills error response structure * @param : msg, information related to message which caused error * @param : err_rsp_info, structure to be filled * @param : index, index of csr message in pending_csr array if parant message is csr * @return : Returns nothing */ void get_error_rsp_info(msg_info *msg, err_rsp_info *err_rsp_info, uint8_t index); /** * @brief : Set and send error response in case of processing update bearer request * @param : msg, holds information related to message caused error * @param : cause_value, cause type of error * @param : cause_source, cause source of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void ubr_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : set and send error response in case of processing delete bearer procedure. * @param : msg, information related to message which caused error * @param : cause value;cause type of error * @param : cause_source, cause source of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void delete_bearer_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : set and send error response in case of processing delete bearer procedure for MME initiated bearer deactivation. * @param : msg, information related to message which caused error * @param : cause value;cause type of error * @param : cause_source, cause source of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void delete_bearer_cmd_failure_indication(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Set and send error response in case of processing Change Notification Request * @param : cause, cause value * @param : cause_source, cause source of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void change_notification_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Set and send error response in case of processing Change Notification Request * @param : msg, message info * @param : cause, cause value * @param : cause_source, cause source of error * @param : iface, interface on which response need to send * @return : Returns nothing */ void release_access_bearer_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Set and send error response in case of processing UPDATE PDN SET CONN. Request * @param : msg, message info * @param : cause, cause value * @param : cause_source, cause source of error * @return : Returns nothing */ void update_pdn_connection_set_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source); /* * @brief : set and send error response in case of processing bearer resource command. * @param : msg, information related to message which caused error * @param : cause value;cause type of error * @param : cause value;cause type of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void send_bearer_resource_failure_indication(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Set and send error response in case of processing create bearer request * @param : msg, holds information related to message caused error * @param : cause_value, cause type of error * @param : cause value;cause type of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void cbr_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Set and send RAA error response in case of reauthentication request failure * @param : pdn, pdn connection information * @param : error, error value * @return : Returns nothing */ void gen_reauth_error_response(pdn_connection *pdn, int16_t error); /** * @brief : Set and send RAA error response in case of wrong seid rcvd * @param : msg, msg information * @param : gxmsg, gx msg information * @param : cause_value, error cause value * @return : Returns nothing */ void gen_reauth_error_resp_for_wrong_seid_rcvd(msg_info *msg, gx_msg *gxmsg, int16_t cause_value); /** * @brief : Preocess sending of ccr-t message if there is any error while procesing gx message * @param : msg, information related to message which caused error * @param : ebi, bearer id * @param : teid, teid value * @return : 0 on success, -1 on failure. */ int send_ccr_t_req(msg_info *msg, uint8_t ebi, uint32_t teid); /** * @brief : Send Version not supported response to peer node. * @param : iface, interface. * @param : seq, sequesnce number. * @return : Returns nothing */ void send_version_not_supported(int iface, uint32_t seq); /** * @brief : Select respective error response function as per proc * @param : msg, message info * @param : cause_value, error cause message * @return : Returns nothing */ void pfcp_modification_error_response(struct resp_info *resp, msg_info *msg, uint8_t cause_value); /** * @brief : Send error in case of fail in DNS. * @param : pdn, PDN connection context information. * @param : cause_value, error cause message * @return : Returns nothing */ void send_error_resp(pdn_connection *pdn, uint8_t cause_value); /** * @brief : Select respective error response function as cca request type * @param : cause, cause value * @param : msg, message info * @return : Returns nothing */ void gx_cca_error_response(uint8_t cause, msg_info *msg); /** * @brief : Cleans upf_context information * @param : pdn, PDN connection context information. * @return : Returns nothing */ void clean_up_upf_context(pdn_connection *pdn, ue_context *context); /** * @brief : cleans context hash * @param : context, * @param : teid, * @param : imsi_val, * @return : Returns nothing */ int clean_context_hash(ue_context *context, uint32_t teid, uint64_t *imsi_val, bool error_status); /** * @brief : Process create indirect data forwarding error response * @param : msg, message info * @param : cause_value, error cause message * @return : Returns nothing */ void crt_indir_data_frwd_tun_error_response(msg_info *msg, uint8_t cause_value); /** * @brief : Process delete indirect data forwarding error response * @param : msg, message info * @param : cause_value, error cause message * @return : Returns nothing */ void delete_indir_data_frwd_error_response(msg_info *msg, uint8_t cause_value); /** * @brief : Process cleanup for indirect tunnel request * @param : resp, err_rsp_info_t * @return : Returns nothing */ void cleanup_for_indirect_tunnel(err_rsp_info *resp); /** * @brief : clears the bearers, pdn, ue_context * @param : teid * @param : ebi_index * @return : Returns -1 on failure and 0 on success. */ int cleanup_ue_and_bearer(uint32_t teid, int ebi_index); /** * @brief : send delete session request to pgwc * @param : context, context information. * @param : ebi_index, Bearer index. * @return : Returns nothing */ void send_delete_session_request_after_timer_retry(ue_context *context, int ebi_index); /** * @brief : set and send error response in case of processing HSS initiated SUB Qos Modification procedure * @param : msg, information related to message which caused error * @param : cause value;cause type of error * @param : cause value;cause type of error * @param : iface, interface on which response to be sent * @return : Returns nothing */ void modify_bearer_failure_indication(msg_info *msg, uint8_t cause_value, uint8_t cause_source, int iface); /** * @brief : Clean up activity to delete bearer if error occurs * @param : pdn ; pdn * @param : context for particular UE * @param : EBI/LBI for Bearer ID * @return : Returns nothing */ void delete_bearer_request_cleanup(pdn_connection *pdn, ue_context *context, uint8_t lbi); /** * @brief : Set and send error response in case of processing modify access bearer request * @param : msg, holds information related to message caused error * @param : cause_value, cause type of error * @param : cause_source, cause source indicates at which source error is generated. * @return : Returns nothing */ void mod_access_bearer_error_response(msg_info *msg, uint8_t cause_value, uint8_t cause_source); #endif
nikhilc149/e-utran-features-bug-fixes
cp/gx_app/include/gx_struct.h
/* * Copyright (c) 2019 Sprint * Copyright (c) 2020 T-Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __GX_STRUCT_H__ #define __GX_STRUCT_H__ #include "gx_def.h" #include "stdint.h" #include "fd.h" #ifdef __cplusplus extern "C" { #endif /******************************************************************************/ /***** OctetString Structures *****/ /******************************************************************************/ typedef struct gxMeasurementQuantityOctetString { uint32_t len; uint8_t val[GX_MEASUREMENT_QUANTITY_LEN + 1]; } GxMeasurementQuantityOctetString; typedef struct gxMdtAllowedPlmnIdOctetString { uint32_t len; uint8_t val[GX_MDT_ALLOWED_PLMN_ID_LEN + 1]; } GxMdtAllowedPlmnIdOctetString; typedef struct gxOriginRealmOctetString { uint32_t len; uint8_t val[GX_ORIGIN_REALM_LEN + 1]; } GxOriginRealmOctetString; typedef struct gx3gppSelectionModeOctetString { uint32_t len; uint8_t val[GX_3GPP_SELECTION_MODE_LEN + 1]; } Gx3gppSelectionModeOctetString; typedef struct gxRoutingRuleIdentifierOctetString { uint32_t len; uint8_t val[GX_ROUTING_RULE_IDENTIFIER_LEN + 1]; } GxRoutingRuleIdentifierOctetString; typedef struct gxTosTrafficClassOctetString { uint32_t len; uint8_t val[GX_TOS_TRAFFIC_CLASS_LEN + 1]; } GxTosTrafficClassOctetString; typedef struct gxRanNasReleaseCauseOctetString { uint32_t len; uint8_t val[GX_RAN_NAS_RELEASE_CAUSE_LEN + 1]; } GxRanNasReleaseCauseOctetString; typedef struct gxPrimaryChargingCollectionFunctionNameOctetString { uint32_t len; uint8_t val[GX_PRIMARY_CHARGING_COLLECTION_FUNCTION_NAME_LEN + 1]; } GxPrimaryChargingCollectionFunctionNameOctetString; typedef struct gxTraceInterfaceListOctetString { uint32_t len; uint8_t val[GX_TRACE_INTERFACE_LIST_LEN + 1]; } GxTraceInterfaceListOctetString; typedef struct gxTraceEventListOctetString { uint32_t len; uint8_t val[GX_TRACE_EVENT_LIST_LEN + 1]; } GxTraceEventListOctetString; typedef struct gx3gppChargingCharacteristicsOctetString { uint32_t len; uint8_t val[GX_3GPP_CHARGING_CHARACTERISTICS_LEN + 1]; } Gx3gppChargingCharacteristicsOctetString; typedef struct gxTdfApplicationInstanceIdentifierOctetString { uint32_t len; uint8_t val[GX_TDF_APPLICATION_INSTANCE_IDENTIFIER_LEN + 1]; } GxTdfApplicationInstanceIdentifierOctetString; typedef struct gxCellGlobalIdentityOctetString { uint32_t len; uint8_t val[GX_CELL_GLOBAL_IDENTITY_LEN + 1]; } GxCellGlobalIdentityOctetString; typedef struct gxPresenceReportingAreaIdentifierOctetString { uint32_t len; uint8_t val[GX_PRESENCE_REPORTING_AREA_IDENTIFIER_LEN + 1]; } GxPresenceReportingAreaIdentifierOctetString; typedef struct gxDefaultQosNameOctetString { uint32_t len; uint8_t val[GX_DEFAULT_QOS_NAME_LEN + 1]; } GxDefaultQosNameOctetString; typedef struct gxBearerIdentifierOctetString { uint32_t len; uint8_t val[GX_BEARER_IDENTIFIER_LEN + 1]; } GxBearerIdentifierOctetString; typedef struct gx3gppGgsnIpv6AddressOctetString { uint32_t len; uint8_t val[GX_3GPP_GGSN_IPV6_ADDRESS_LEN + 1]; } Gx3gppGgsnIpv6AddressOctetString; typedef struct gx3gpp2BsidOctetString { uint32_t len; uint8_t val[GX_3GPP2_BSID_LEN + 1]; } Gx3gpp2BsidOctetString; typedef struct gxOriginHostOctetString { uint32_t len; uint8_t val[GX_ORIGIN_HOST_LEN + 1]; } GxOriginHostOctetString; typedef struct gxServiceContextIdOctetString { uint32_t len; uint8_t val[GX_SERVICE_CONTEXT_ID_LEN + 1]; } GxServiceContextIdOctetString; typedef struct gxPacketFilterIdentifierOctetString { uint32_t len; uint8_t val[GX_PACKET_FILTER_IDENTIFIER_LEN + 1]; } GxPacketFilterIdentifierOctetString; typedef struct gxPhysicalAccessIdOctetString { uint32_t len; uint8_t val[GX_PHYSICAL_ACCESS_ID_LEN + 1]; } GxPhysicalAccessIdOctetString; typedef struct gxTunnelHeaderFilterOctetString { uint32_t len; uint8_t val[GX_TUNNEL_HEADER_FILTER_LEN + 1]; } GxTunnelHeaderFilterOctetString; typedef struct gxTraceNeTypeListOctetString { uint32_t len; uint8_t val[GX_TRACE_NE_TYPE_LIST_LEN + 1]; } GxTraceNeTypeListOctetString; typedef struct gxSecondaryEventChargingFunctionNameOctetString { uint32_t len; uint8_t val[GX_SECONDARY_EVENT_CHARGING_FUNCTION_NAME_LEN + 1]; } GxSecondaryEventChargingFunctionNameOctetString; typedef struct gxAccessNetworkChargingIdentifierValueOctetString { uint32_t len; uint8_t val[GX_ACCESS_NETWORK_CHARGING_IDENTIFIER_VALUE_LEN + 1]; } GxAccessNetworkChargingIdentifierValueOctetString; typedef struct gxSourceidOctetString { uint32_t len; uint8_t val[GX_SOURCEID_LEN + 1]; } GxSourceidOctetString; typedef struct gxChargingRuleNameOctetString { uint32_t len; uint8_t val[GX_CHARGING_RULE_NAME_LEN + 1]; } GxChargingRuleNameOctetString; typedef struct gxErrorMessageOctetString { uint32_t len; uint8_t val[GX_ERROR_MESSAGE_LEN + 1]; } GxErrorMessageOctetString; typedef struct gxSubscriptionIdDataOctetString { uint32_t len; uint8_t val[GX_SUBSCRIPTION_ID_DATA_LEN + 1]; } GxSubscriptionIdDataOctetString; typedef struct gx3gppSgsnMccMncOctetString { uint32_t len; uint8_t val[GX_3GPP_SGSN_MCC_MNC_LEN + 1]; } Gx3gppSgsnMccMncOctetString; typedef struct gxRaiOctetString { uint32_t len; uint8_t val[GX_RAI_LEN + 1]; } GxRaiOctetString; typedef struct gxUserEquipmentInfoValueOctetString { uint32_t len; uint8_t val[GX_USER_EQUIPMENT_INFO_VALUE_LEN + 1]; } GxUserEquipmentInfoValueOctetString; typedef struct gxFlowDescriptionOctetString { uint32_t len; uint8_t val[GX_FLOW_DESCRIPTION_LEN + 1]; } GxFlowDescriptionOctetString; typedef struct gxTdfDestinationRealmOctetString { uint32_t len; uint8_t val[GX_TDF_DESTINATION_REALM_LEN + 1]; } GxTdfDestinationRealmOctetString; typedef struct gxFilterIdOctetString { uint32_t len; uint8_t val[GX_FILTER_ID_LEN + 1]; } GxFilterIdOctetString; typedef struct gx3gppRatTypeOctetString { uint32_t len; uint8_t val[GX_3GPP_RAT_TYPE_LEN + 1]; } Gx3gppRatTypeOctetString; typedef struct gxPdnConnectionIdOctetString { uint32_t len; uint8_t val[GX_PDN_CONNECTION_ID_LEN + 1]; } GxPdnConnectionIdOctetString; typedef struct gxChargingRuleBaseNameOctetString { uint32_t len; uint8_t val[GX_CHARGING_RULE_BASE_NAME_LEN + 1]; } GxChargingRuleBaseNameOctetString; typedef struct gxFramedIpAddressOctetString { uint32_t len; uint8_t val[GX_FRAMED_IP_ADDRESS_LEN + 1]; } GxFramedIpAddressOctetString; typedef struct gxLogicalAccessIdOctetString { uint32_t len; uint8_t val[GX_LOGICAL_ACCESS_ID_LEN + 1]; } GxLogicalAccessIdOctetString; typedef struct gxFramedIpv6PrefixOctetString { uint32_t len; uint8_t val[GX_FRAMED_IPV6_PREFIX_LEN + 1]; } GxFramedIpv6PrefixOctetString; typedef struct gxEUtranCellGlobalIdentityOctetString { uint32_t len; uint8_t val[GX_E_UTRAN_CELL_GLOBAL_IDENTITY_LEN + 1]; } GxEUtranCellGlobalIdentityOctetString; typedef struct gxLocationAreaIdentityOctetString { uint32_t len; uint8_t val[GX_LOCATION_AREA_IDENTITY_LEN + 1]; } GxLocationAreaIdentityOctetString; typedef struct gxSecurityParameterIndexOctetString { uint32_t len; uint8_t val[GX_SECURITY_PARAMETER_INDEX_LEN + 1]; } GxSecurityParameterIndexOctetString; typedef struct gxTdfDestinationHostOctetString { uint32_t len; uint8_t val[GX_TDF_DESTINATION_HOST_LEN + 1]; } GxTdfDestinationHostOctetString; typedef struct gxRoutingAreaIdentityOctetString { uint32_t len; uint8_t val[GX_ROUTING_AREA_IDENTITY_LEN + 1]; } GxRoutingAreaIdentityOctetString; typedef struct gxTrackingAreaIdentityOctetString { uint32_t len; uint8_t val[GX_TRACKING_AREA_IDENTITY_LEN + 1]; } GxTrackingAreaIdentityOctetString; typedef struct gx3gppMsTimezoneOctetString { uint32_t len; uint8_t val[GX_3GPP_MS_TIMEZONE_LEN + 1]; } Gx3gppMsTimezoneOctetString; typedef struct gxPresenceReportingAreaElementsListOctetString { uint32_t len; uint8_t val[GX_PRESENCE_REPORTING_AREA_ELEMENTS_LIST_LEN + 1]; } GxPresenceReportingAreaElementsListOctetString; typedef struct gxTwanIdentifierOctetString { uint32_t len; uint8_t val[GX_TWAN_IDENTIFIER_LEN + 1]; } GxTwanIdentifierOctetString; typedef struct gxSessionIdOctetString { uint32_t len; uint8_t val[GX_SESSION_ID_LEN + 1]; } GxSessionIdOctetString; typedef struct gx3gppUserLocationInfoOctetString { uint32_t len; uint8_t val[GX_3GPP_USER_LOCATION_INFO_LEN + 1]; } Gx3gppUserLocationInfoOctetString; typedef struct gxRestrictionFilterRuleOctetString { uint32_t len; uint8_t val[GX_RESTRICTION_FILTER_RULE_LEN + 1]; } GxRestrictionFilterRuleOctetString; typedef struct gxSecondaryChargingCollectionFunctionNameOctetString { uint32_t len; uint8_t val[GX_SECONDARY_CHARGING_COLLECTION_FUNCTION_NAME_LEN + 1]; } GxSecondaryChargingCollectionFunctionNameOctetString; typedef struct gxApplicationServiceProviderIdentityOctetString { uint32_t len; uint8_t val[GX_APPLICATION_SERVICE_PROVIDER_IDENTITY_LEN + 1]; } GxApplicationServiceProviderIdentityOctetString; typedef struct gxTftFilterOctetString { uint32_t len; uint8_t val[GX_TFT_FILTER_LEN + 1]; } GxTftFilterOctetString; typedef struct gxTrafficSteeringPolicyIdentifierDlOctetString { uint32_t len; uint8_t val[GX_TRAFFIC_STEERING_POLICY_IDENTIFIER_DL_LEN + 1]; } GxTrafficSteeringPolicyIdentifierDlOctetString; typedef struct gxPrimaryEventChargingFunctionNameOctetString { uint32_t len; uint8_t val[GX_PRIMARY_EVENT_CHARGING_FUNCTION_NAME_LEN + 1]; } GxPrimaryEventChargingFunctionNameOctetString; typedef struct gxTraceReferenceOctetString { uint32_t len; uint8_t val[GX_TRACE_REFERENCE_LEN + 1]; } GxTraceReferenceOctetString; typedef struct gxOmcIdOctetString { uint32_t len; uint8_t val[GX_OMC_ID_LEN + 1]; } GxOmcIdOctetString; typedef struct gxSsidOctetString { uint32_t len; uint8_t val[GX_SSID_LEN + 1]; } GxSsidOctetString; typedef struct gxBssidOctetString { uint32_t len; uint8_t val[GX_BSSID_LEN + 1]; } GxBssidOctetString; typedef struct gxProxyHostOctetString { uint32_t len; uint8_t val[GX_PROXY_HOST_LEN + 1]; } GxProxyHostOctetString; typedef struct gxDestinationRealmOctetString { uint32_t len; uint8_t val[GX_DESTINATION_REALM_LEN + 1]; } GxDestinationRealmOctetString; typedef struct gxPacketFilterContentOctetString { uint32_t len; uint8_t val[GX_PACKET_FILTER_CONTENT_LEN + 1]; } GxPacketFilterContentOctetString; typedef struct gxSponsorIdentityOctetString { uint32_t len; uint8_t val[GX_SPONSOR_IDENTITY_LEN + 1]; } GxSponsorIdentityOctetString; typedef struct gx3gppGgsnAddressOctetString { uint32_t len; uint8_t val[GX_3GPP_GGSN_ADDRESS_LEN + 1]; } Gx3gppGgsnAddressOctetString; typedef struct gxDestinationHostOctetString { uint32_t len; uint8_t val[GX_DESTINATION_HOST_LEN + 1]; } GxDestinationHostOctetString; typedef struct gxProxyStateOctetString { uint32_t len; uint8_t val[GX_PROXY_STATE_LEN + 1]; } GxProxyStateOctetString; typedef struct gxRedirectServerAddressOctetString { uint32_t len; uint8_t val[GX_REDIRECT_SERVER_ADDRESS_LEN + 1]; } GxRedirectServerAddressOctetString; typedef struct gxRedirectHostOctetString { uint32_t len; uint8_t val[GX_REDIRECT_HOST_LEN + 1]; } GxRedirectHostOctetString; typedef struct gxTdfApplicationIdentifierOctetString { uint32_t len; uint8_t val[GX_TDF_APPLICATION_IDENTIFIER_LEN + 1]; } GxTdfApplicationIdentifierOctetString; typedef struct gxFlowLabelOctetString { uint32_t len; uint8_t val[GX_FLOW_LABEL_LEN + 1]; } GxFlowLabelOctetString; typedef struct gxCalledStationIdOctetString { uint32_t len; uint8_t val[GX_CALLED_STATION_ID_LEN + 1]; } GxCalledStationIdOctetString; typedef struct gxAfChargingIdentifierOctetString { uint32_t len; uint8_t val[GX_AF_CHARGING_IDENTIFIER_LEN + 1]; } GxAfChargingIdentifierOctetString; typedef struct gx3gppSgsnAddressOctetString { uint32_t len; uint8_t val[GX_3GPP_SGSN_ADDRESS_LEN + 1]; } Gx3gppSgsnAddressOctetString; typedef struct gxTrafficSteeringPolicyIdentifierUlOctetString { uint32_t len; uint8_t val[GX_TRAFFIC_STEERING_POLICY_IDENTIFIER_UL_LEN + 1]; } GxTrafficSteeringPolicyIdentifierUlOctetString; typedef struct gxPositioningMethodOctetString { uint32_t len; uint8_t val[GX_POSITIONING_METHOD_LEN + 1]; } GxPositioningMethodOctetString; typedef struct gxMonitoringKeyOctetString { uint32_t len; uint8_t val[GX_MONITORING_KEY_LEN + 1]; } GxMonitoringKeyOctetString; typedef struct gxRouteRecordOctetString { uint32_t len; uint8_t val[GX_ROUTE_RECORD_LEN + 1]; } GxRouteRecordOctetString; typedef struct gxErrorReportingHostOctetString { uint32_t len; uint8_t val[GX_ERROR_REPORTING_HOST_LEN + 1]; } GxErrorReportingHostOctetString; typedef struct gx3gppSgsnIpv6AddressOctetString { uint32_t len; uint8_t val[GX_3GPP_SGSN_IPV6_ADDRESS_LEN + 1]; } Gx3gppSgsnIpv6AddressOctetString; /******************************************************************************/ /***** Presence Structures *****/ /******************************************************************************/ typedef struct gxExperimentalResultPresence { unsigned int vendor_id : 1; unsigned int experimental_result_code : 1; } GxExperimentalResultPresence; typedef struct gxPraRemovePresence { unsigned int presence_reporting_area_identifier : 1; } GxPraRemovePresence; typedef struct gxQosInformationPresence { unsigned int qos_class_identifier : 1; unsigned int max_requested_bandwidth_ul : 1; unsigned int max_requested_bandwidth_dl : 1; unsigned int extended_max_requested_bw_ul : 1; unsigned int extended_max_requested_bw_dl : 1; unsigned int guaranteed_bitrate_ul : 1; unsigned int guaranteed_bitrate_dl : 1; unsigned int extended_gbr_ul : 1; unsigned int extended_gbr_dl : 1; unsigned int bearer_identifier : 1; unsigned int allocation_retention_priority : 1; unsigned int apn_aggregate_max_bitrate_ul : 1; unsigned int apn_aggregate_max_bitrate_dl : 1; unsigned int extended_apn_ambr_ul : 1; unsigned int extended_apn_ambr_dl : 1; unsigned int conditional_apn_aggregate_max_bitrate : 1; } GxQosInformationPresence; typedef struct gxConditionalPolicyInformationPresence { unsigned int execution_time : 1; unsigned int default_eps_bearer_qos : 1; unsigned int apn_aggregate_max_bitrate_ul : 1; unsigned int apn_aggregate_max_bitrate_dl : 1; unsigned int extended_apn_ambr_ul : 1; unsigned int extended_apn_ambr_dl : 1; unsigned int conditional_apn_aggregate_max_bitrate : 1; } GxConditionalPolicyInformationPresence; typedef struct gxPraInstallPresence { unsigned int presence_reporting_area_information : 1; } GxPraInstallPresence; typedef struct gxAreaScopePresence { unsigned int cell_global_identity : 1; unsigned int e_utran_cell_global_identity : 1; unsigned int routing_area_identity : 1; unsigned int location_area_identity : 1; unsigned int tracking_area_identity : 1; } GxAreaScopePresence; typedef struct gxFlowInformationPresence { unsigned int flow_description : 1; unsigned int packet_filter_identifier : 1; unsigned int packet_filter_usage : 1; unsigned int tos_traffic_class : 1; unsigned int security_parameter_index : 1; unsigned int flow_label : 1; unsigned int flow_direction : 1; unsigned int routing_rule_identifier : 1; } GxFlowInformationPresence; typedef struct gxTunnelInformationPresence { unsigned int tunnel_header_length : 1; unsigned int tunnel_header_filter : 1; } GxTunnelInformationPresence; typedef struct gxTftPacketFilterInformationPresence { unsigned int precedence : 1; unsigned int tft_filter : 1; unsigned int tos_traffic_class : 1; unsigned int security_parameter_index : 1; unsigned int flow_label : 1; unsigned int flow_direction : 1; } GxTftPacketFilterInformationPresence; typedef struct gxMbsfnAreaPresence { unsigned int mbsfn_area_id : 1; unsigned int carrier_frequency : 1; } GxMbsfnAreaPresence; typedef struct gxEventReportIndicationPresence { unsigned int an_trusted : 1; unsigned int event_trigger : 1; unsigned int user_csg_information : 1; unsigned int ip_can_type : 1; unsigned int an_gw_address : 1; unsigned int tgpp_sgsn_address : 1; unsigned int tgpp_sgsn_ipv6_address : 1; unsigned int tgpp_sgsn_mcc_mnc : 1; unsigned int framed_ip_address : 1; unsigned int rat_type : 1; unsigned int rai : 1; unsigned int tgpp_user_location_info : 1; unsigned int trace_data : 1; unsigned int trace_reference : 1; unsigned int tgpp2_bsid : 1; unsigned int tgpp_ms_timezone : 1; unsigned int routing_ip_address : 1; unsigned int ue_local_ip_address : 1; unsigned int henb_local_ip_address : 1; unsigned int udp_source_port : 1; unsigned int presence_reporting_area_information : 1; } GxEventReportIndicationPresence; typedef struct gxTdfInformationPresence { unsigned int tdf_destination_realm : 1; unsigned int tdf_destination_host : 1; unsigned int tdf_ip_address : 1; } GxTdfInformationPresence; typedef struct gxProxyInfoPresence { unsigned int proxy_host : 1; unsigned int proxy_state : 1; } GxProxyInfoPresence; typedef struct gxUsedServiceUnitPresence { unsigned int reporting_reason : 1; unsigned int tariff_change_usage : 1; unsigned int cc_time : 1; unsigned int cc_money : 1; unsigned int cc_total_octets : 1; unsigned int cc_input_octets : 1; unsigned int cc_output_octets : 1; unsigned int cc_service_specific_units : 1; unsigned int event_charging_timestamp : 1; } GxUsedServiceUnitPresence; typedef struct gxChargingRuleInstallPresence { unsigned int charging_rule_definition : 1; unsigned int charging_rule_name : 1; unsigned int charging_rule_base_name : 1; unsigned int bearer_identifier : 1; unsigned int monitoring_flags : 1; unsigned int rule_activation_time : 1; unsigned int rule_deactivation_time : 1; unsigned int resource_allocation_notification : 1; unsigned int charging_correlation_indicator : 1; unsigned int ip_can_type : 1; } GxChargingRuleInstallPresence; typedef struct gxChargingRuleDefinitionPresence { unsigned int charging_rule_name : 1; unsigned int service_identifier : 1; unsigned int rating_group : 1; unsigned int flow_information : 1; unsigned int default_bearer_indication : 1; unsigned int tdf_application_identifier : 1; unsigned int flow_status : 1; unsigned int qos_information : 1; unsigned int ps_to_cs_session_continuity : 1; unsigned int reporting_level : 1; unsigned int online : 1; unsigned int offline : 1; unsigned int max_plr_dl : 1; unsigned int max_plr_ul : 1; unsigned int metering_method : 1; unsigned int precedence : 1; unsigned int af_charging_identifier : 1; unsigned int flows : 1; unsigned int monitoring_key : 1; unsigned int redirect_information : 1; unsigned int mute_notification : 1; unsigned int af_signalling_protocol : 1; unsigned int sponsor_identity : 1; unsigned int application_service_provider_identity : 1; unsigned int required_access_info : 1; unsigned int sharing_key_dl : 1; unsigned int sharing_key_ul : 1; unsigned int traffic_steering_policy_identifier_dl : 1; unsigned int traffic_steering_policy_identifier_ul : 1; unsigned int content_version : 1; } GxChargingRuleDefinitionPresence; typedef struct gxFinalUnitIndicationPresence { unsigned int final_unit_action : 1; unsigned int restriction_filter_rule : 1; unsigned int filter_id : 1; unsigned int redirect_server : 1; } GxFinalUnitIndicationPresence; typedef struct gxUnitValuePresence { unsigned int value_digits : 1; unsigned int exponent : 1; } GxUnitValuePresence; typedef struct gxPresenceReportingAreaInformationPresence { unsigned int presence_reporting_area_identifier : 1; unsigned int presence_reporting_area_status : 1; unsigned int presence_reporting_area_elements_list : 1; unsigned int presence_reporting_area_node : 1; } GxPresenceReportingAreaInformationPresence; typedef struct gxConditionalApnAggregateMaxBitratePresence { unsigned int apn_aggregate_max_bitrate_ul : 1; unsigned int apn_aggregate_max_bitrate_dl : 1; unsigned int extended_apn_ambr_ul : 1; unsigned int extended_apn_ambr_dl : 1; unsigned int ip_can_type : 1; unsigned int rat_type : 1; } GxConditionalApnAggregateMaxBitratePresence; typedef struct gxAccessNetworkChargingIdentifierGxPresence { unsigned int access_network_charging_identifier_value : 1; unsigned int charging_rule_base_name : 1; unsigned int charging_rule_name : 1; unsigned int ip_can_session_charging_scope : 1; } GxAccessNetworkChargingIdentifierGxPresence; typedef struct gxOcOlrPresence { unsigned int oc_sequence_number : 1; unsigned int oc_report_type : 1; unsigned int oc_reduction_percentage : 1; unsigned int oc_validity_duration : 1; } GxOcOlrPresence; typedef struct gxRoutingRuleInstallPresence { unsigned int routing_rule_definition : 1; } GxRoutingRuleInstallPresence; typedef struct gxTraceDataPresence { unsigned int trace_reference : 1; unsigned int trace_depth : 1; unsigned int trace_ne_type_list : 1; unsigned int trace_interface_list : 1; unsigned int trace_event_list : 1; unsigned int omc_id : 1; unsigned int trace_collection_entity : 1; unsigned int mdt_configuration : 1; } GxTraceDataPresence; typedef struct gxRoutingRuleDefinitionPresence { unsigned int routing_rule_identifier : 1; unsigned int routing_filter : 1; unsigned int precedence : 1; unsigned int routing_ip_address : 1; unsigned int ip_can_type : 1; } GxRoutingRuleDefinitionPresence; typedef struct gxMdtConfigurationPresence { unsigned int job_type : 1; unsigned int area_scope : 1; unsigned int list_of_measurements : 1; unsigned int reporting_trigger : 1; unsigned int report_interval : 1; unsigned int report_amount : 1; unsigned int event_threshold_rsrp : 1; unsigned int event_threshold_rsrq : 1; unsigned int logging_interval : 1; unsigned int logging_duration : 1; unsigned int measurement_period_lte : 1; unsigned int measurement_period_umts : 1; unsigned int collection_period_rrm_lte : 1; unsigned int collection_period_rrm_umts : 1; unsigned int positioning_method : 1; unsigned int measurement_quantity : 1; unsigned int event_threshold_event_1f : 1; unsigned int event_threshold_event_1i : 1; unsigned int mdt_allowed_plmn_id : 1; unsigned int mbsfn_area : 1; } GxMdtConfigurationPresence; typedef struct gxChargingRuleRemovePresence { unsigned int charging_rule_name : 1; unsigned int charging_rule_base_name : 1; unsigned int required_access_info : 1; unsigned int resource_release_notification : 1; } GxChargingRuleRemovePresence; typedef struct gxAllocationRetentionPriorityPresence { unsigned int priority_level : 1; unsigned int pre_emption_capability : 1; unsigned int pre_emption_vulnerability : 1; } GxAllocationRetentionPriorityPresence; typedef struct gxDefaultEpsBearerQosPresence { unsigned int qos_class_identifier : 1; unsigned int allocation_retention_priority : 1; } GxDefaultEpsBearerQosPresence; typedef struct gxRoutingRuleReportPresence { unsigned int routing_rule_identifier : 1; unsigned int pcc_rule_status : 1; unsigned int routing_rule_failure_code : 1; } GxRoutingRuleReportPresence; typedef struct gxUserEquipmentInfoPresence { unsigned int user_equipment_info_type : 1; unsigned int user_equipment_info_value : 1; } GxUserEquipmentInfoPresence; typedef struct gxSupportedFeaturesPresence { unsigned int vendor_id : 1; unsigned int feature_list_id : 1; unsigned int feature_list : 1; } GxSupportedFeaturesPresence; typedef struct gxFixedUserLocationInfoPresence { unsigned int ssid : 1; unsigned int bssid : 1; unsigned int logical_access_id : 1; unsigned int physical_access_id : 1; } GxFixedUserLocationInfoPresence; typedef struct gxDefaultQosInformationPresence { unsigned int qos_class_identifier : 1; unsigned int max_requested_bandwidth_ul : 1; unsigned int max_requested_bandwidth_dl : 1; unsigned int default_qos_name : 1; } GxDefaultQosInformationPresence; typedef struct gxLoadPresence { unsigned int load_type : 1; unsigned int load_value : 1; unsigned int sourceid : 1; } GxLoadPresence; typedef struct gxRedirectServerPresence { unsigned int redirect_address_type : 1; unsigned int redirect_server_address : 1; } GxRedirectServerPresence; typedef struct gxOcSupportedFeaturesPresence { unsigned int oc_feature_vector : 1; } GxOcSupportedFeaturesPresence; typedef struct gxPacketFilterInformationPresence { unsigned int packet_filter_identifier : 1; unsigned int precedence : 1; unsigned int packet_filter_content : 1; unsigned int tos_traffic_class : 1; unsigned int security_parameter_index : 1; unsigned int flow_label : 1; unsigned int flow_direction : 1; } GxPacketFilterInformationPresence; typedef struct gxSubscriptionIdPresence { unsigned int subscription_id_type : 1; unsigned int subscription_id_data : 1; } GxSubscriptionIdPresence; typedef struct gxChargingInformationPresence { unsigned int primary_event_charging_function_name : 1; unsigned int secondary_event_charging_function_name : 1; unsigned int primary_charging_collection_function_name : 1; unsigned int secondary_charging_collection_function_name : 1; } GxChargingInformationPresence; typedef struct gxUsageMonitoringInformationPresence { unsigned int monitoring_key : 1; unsigned int granted_service_unit : 1; unsigned int used_service_unit : 1; unsigned int quota_consumption_time : 1; unsigned int usage_monitoring_level : 1; unsigned int usage_monitoring_report : 1; unsigned int usage_monitoring_support : 1; } GxUsageMonitoringInformationPresence; typedef struct gxChargingRuleReportPresence { unsigned int charging_rule_name : 1; unsigned int charging_rule_base_name : 1; unsigned int bearer_identifier : 1; unsigned int pcc_rule_status : 1; unsigned int rule_failure_code : 1; unsigned int final_unit_indication : 1; unsigned int ran_nas_release_cause : 1; unsigned int content_version : 1; } GxChargingRuleReportPresence; typedef struct gxRedirectInformationPresence { unsigned int redirect_support : 1; unsigned int redirect_address_type : 1; unsigned int redirect_server_address : 1; } GxRedirectInformationPresence; typedef struct gxFailedAvpPresence { } GxFailedAvpPresence; typedef struct gxRoutingRuleRemovePresence { unsigned int routing_rule_identifier : 1; } GxRoutingRuleRemovePresence; typedef struct gxRoutingFilterPresence { unsigned int flow_description : 1; unsigned int flow_direction : 1; unsigned int tos_traffic_class : 1; unsigned int security_parameter_index : 1; unsigned int flow_label : 1; } GxRoutingFilterPresence; typedef struct gxCoaInformationPresence { unsigned int tunnel_information : 1; unsigned int coa_ip_address : 1; } GxCoaInformationPresence; typedef struct gxGrantedServiceUnitPresence { unsigned int tariff_time_change : 1; unsigned int cc_time : 1; unsigned int cc_money : 1; unsigned int cc_total_octets : 1; unsigned int cc_input_octets : 1; unsigned int cc_output_octets : 1; unsigned int cc_service_specific_units : 1; } GxGrantedServiceUnitPresence; typedef struct gxCcMoneyPresence { unsigned int unit_value : 1; unsigned int currency_code : 1; } GxCcMoneyPresence; typedef struct gxApplicationDetectionInformationPresence { unsigned int tdf_application_identifier : 1; unsigned int tdf_application_instance_identifier : 1; unsigned int flow_information : 1; } GxApplicationDetectionInformationPresence; typedef struct gxFlowsPresence { unsigned int media_component_number : 1; unsigned int flow_number : 1; unsigned int content_version : 1; unsigned int final_unit_action : 1; unsigned int media_component_status : 1; } GxFlowsPresence; typedef struct gxUserCsgInformationPresence { unsigned int csg_id : 1; unsigned int csg_access_mode : 1; unsigned int csg_membership_indication : 1; } GxUserCsgInformationPresence; typedef struct gxRarPresence { unsigned int session_id : 1; unsigned int drmp : 1; unsigned int auth_application_id : 1; unsigned int origin_host : 1; unsigned int origin_realm : 1; unsigned int destination_realm : 1; unsigned int destination_host : 1; unsigned int re_auth_request_type : 1; unsigned int session_release_cause : 1; unsigned int origin_state_id : 1; unsigned int oc_supported_features : 1; unsigned int event_trigger : 1; unsigned int event_report_indication : 1; unsigned int charging_rule_remove : 1; unsigned int charging_rule_install : 1; unsigned int default_eps_bearer_qos : 1; unsigned int qos_information : 1; unsigned int default_qos_information : 1; unsigned int revalidation_time : 1; unsigned int usage_monitoring_information : 1; unsigned int pcscf_restoration_indication : 1; unsigned int conditional_policy_information : 1; unsigned int removal_of_access : 1; unsigned int ip_can_type : 1; unsigned int pra_install : 1; unsigned int pra_remove : 1; unsigned int csg_information_reporting : 1; unsigned int proxy_info : 1; unsigned int route_record : 1; } GxRarPresence; typedef struct gxRaaPresence { unsigned int session_id : 1; unsigned int drmp : 1; unsigned int origin_host : 1; unsigned int origin_realm : 1; unsigned int result_code : 1; unsigned int experimental_result : 1; unsigned int origin_state_id : 1; unsigned int oc_supported_features : 1; unsigned int oc_olr : 1; unsigned int ip_can_type : 1; unsigned int rat_type : 1; unsigned int an_trusted : 1; unsigned int an_gw_address : 1; unsigned int tgpp_sgsn_mcc_mnc : 1; unsigned int tgpp_sgsn_address : 1; unsigned int tgpp_sgsn_ipv6_address : 1; unsigned int rai : 1; unsigned int tgpp_user_location_info : 1; unsigned int user_location_info_time : 1; unsigned int netloc_access_support : 1; unsigned int user_csg_information : 1; unsigned int tgpp_ms_timezone : 1; unsigned int default_qos_information : 1; unsigned int charging_rule_report : 1; unsigned int error_message : 1; unsigned int error_reporting_host : 1; unsigned int failed_avp : 1; unsigned int proxy_info : 1; } GxRaaPresence; typedef struct gxCcaPresence { unsigned int session_id : 1; unsigned int drmp : 1; unsigned int auth_application_id : 1; unsigned int origin_host : 1; unsigned int origin_realm : 1; unsigned int result_code : 1; unsigned int experimental_result : 1; unsigned int cc_request_type : 1; unsigned int cc_request_number : 1; unsigned int oc_supported_features : 1; unsigned int oc_olr : 1; unsigned int supported_features : 1; unsigned int bearer_control_mode : 1; unsigned int event_trigger : 1; unsigned int event_report_indication : 1; unsigned int origin_state_id : 1; unsigned int redirect_host : 1; unsigned int redirect_host_usage : 1; unsigned int redirect_max_cache_time : 1; unsigned int charging_rule_remove : 1; unsigned int charging_rule_install : 1; unsigned int charging_information : 1; unsigned int online : 1; unsigned int offline : 1; unsigned int qos_information : 1; unsigned int revalidation_time : 1; unsigned int default_eps_bearer_qos : 1; unsigned int default_qos_information : 1; unsigned int bearer_usage : 1; unsigned int usage_monitoring_information : 1; unsigned int csg_information_reporting : 1; unsigned int user_csg_information : 1; unsigned int pra_install : 1; unsigned int pra_remove : 1; unsigned int presence_reporting_area_information : 1; unsigned int session_release_cause : 1; unsigned int nbifom_support : 1; unsigned int nbifom_mode : 1; unsigned int default_access : 1; unsigned int ran_rule_support : 1; unsigned int routing_rule_report : 1; unsigned int conditional_policy_information : 1; unsigned int removal_of_access : 1; unsigned int ip_can_type : 1; unsigned int error_message : 1; unsigned int error_reporting_host : 1; unsigned int failed_avp : 1; unsigned int proxy_info : 1; unsigned int route_record : 1; unsigned int load : 1; } GxCcaPresence; typedef struct gxCcrPresence { unsigned int session_id : 1; unsigned int drmp : 1; unsigned int auth_application_id : 1; unsigned int origin_host : 1; unsigned int origin_realm : 1; unsigned int destination_realm : 1; unsigned int service_context_id : 1; unsigned int cc_request_type : 1; unsigned int cc_request_number : 1; unsigned int credit_management_status : 1; unsigned int destination_host : 1; unsigned int origin_state_id : 1; unsigned int subscription_id : 1; unsigned int oc_supported_features : 1; unsigned int supported_features : 1; unsigned int tdf_information : 1; unsigned int network_request_support : 1; unsigned int packet_filter_information : 1; unsigned int packet_filter_operation : 1; unsigned int bearer_identifier : 1; unsigned int bearer_operation : 1; unsigned int dynamic_address_flag : 1; unsigned int dynamic_address_flag_extension : 1; unsigned int pdn_connection_charging_id : 1; unsigned int framed_ip_address : 1; unsigned int framed_ipv6_prefix : 1; unsigned int ip_can_type : 1; unsigned int tgpp_rat_type : 1; unsigned int an_trusted : 1; unsigned int rat_type : 1; unsigned int termination_cause : 1; unsigned int user_equipment_info : 1; unsigned int qos_information : 1; unsigned int qos_negotiation : 1; unsigned int qos_upgrade : 1; unsigned int default_eps_bearer_qos : 1; unsigned int default_qos_information : 1; unsigned int an_gw_address : 1; unsigned int an_gw_status : 1; unsigned int tgpp_sgsn_mcc_mnc : 1; unsigned int tgpp_sgsn_address : 1; unsigned int tgpp_sgsn_ipv6_address : 1; unsigned int tgpp_ggsn_address : 1; unsigned int tgpp_ggsn_ipv6_address : 1; unsigned int tgpp_selection_mode : 1; unsigned int rai : 1; unsigned int tgpp_user_location_info : 1; unsigned int fixed_user_location_info : 1; unsigned int user_location_info_time : 1; unsigned int user_csg_information : 1; unsigned int twan_identifier : 1; unsigned int tgpp_ms_timezone : 1; unsigned int ran_nas_release_cause : 1; unsigned int tgpp_charging_characteristics : 1; unsigned int called_station_id : 1; unsigned int pdn_connection_id : 1; unsigned int bearer_usage : 1; unsigned int online : 1; unsigned int offline : 1; unsigned int tft_packet_filter_information : 1; unsigned int charging_rule_report : 1; unsigned int application_detection_information : 1; unsigned int event_trigger : 1; unsigned int event_report_indication : 1; unsigned int access_network_charging_address : 1; unsigned int access_network_charging_identifier_gx : 1; unsigned int coa_information : 1; unsigned int usage_monitoring_information : 1; unsigned int nbifom_support : 1; unsigned int nbifom_mode : 1; unsigned int default_access : 1; unsigned int origination_time_stamp : 1; unsigned int maximum_wait_time : 1; unsigned int access_availability_change_reason : 1; unsigned int routing_rule_install : 1; unsigned int routing_rule_remove : 1; unsigned int henb_local_ip_address : 1; unsigned int ue_local_ip_address : 1; unsigned int udp_source_port : 1; unsigned int tcp_source_port : 1; unsigned int presence_reporting_area_information : 1; unsigned int logical_access_id : 1; unsigned int physical_access_id : 1; unsigned int proxy_info : 1; unsigned int route_record : 1; unsigned int tgpp_ps_data_off_status : 1; } GxCcrPresence; /******************************************************************************/ /***** Grouped AVP Structures *****/ /******************************************************************************/ typedef struct gxRouteRecordList { int32_t count; GxRouteRecordOctetString *list; } GxRouteRecordList; typedef struct gxProxyInfo { GxProxyInfoPresence presence; GxProxyHostOctetString proxy_host; GxProxyStateOctetString proxy_state; } GxProxyInfo; typedef struct gxProxyInfoList { int32_t count; GxProxyInfo *list; } GxProxyInfoList; typedef struct gxPresenceReportingAreaInformation { GxPresenceReportingAreaInformationPresence presence; GxPresenceReportingAreaIdentifierOctetString presence_reporting_area_identifier; uint32_t presence_reporting_area_status; GxPresenceReportingAreaElementsListOctetString presence_reporting_area_elements_list; uint32_t presence_reporting_area_node; } GxPresenceReportingAreaInformation; typedef struct gxPresenceReportingAreaInformationList { int32_t count; GxPresenceReportingAreaInformation *list; } GxPresenceReportingAreaInformationList; typedef struct gxRoutingRuleIdentifierList { int32_t count; GxRoutingRuleIdentifierOctetString *list; } GxRoutingRuleIdentifierList; typedef struct gxRoutingRuleRemove { GxRoutingRuleRemovePresence presence; GxRoutingRuleIdentifierList routing_rule_identifier; } GxRoutingRuleRemove; typedef struct gxRoutingFilter { GxRoutingFilterPresence presence; GxFlowDescriptionOctetString flow_description; int32_t flow_direction; GxTosTrafficClassOctetString tos_traffic_class; GxSecurityParameterIndexOctetString security_parameter_index; GxFlowLabelOctetString flow_label; } GxRoutingFilter; typedef struct gxRoutingFilterList { int32_t count; GxRoutingFilter *list; } GxRoutingFilterList; typedef struct gxRoutingRuleDefinition { GxRoutingRuleDefinitionPresence presence; GxRoutingRuleIdentifierOctetString routing_rule_identifier; GxRoutingFilterList routing_filter; uint32_t precedence; FdAddress routing_ip_address; int32_t ip_can_type; } GxRoutingRuleDefinition; typedef struct gxRoutingRuleDefinitionList { int32_t count; GxRoutingRuleDefinition *list; } GxRoutingRuleDefinitionList; typedef struct gxRoutingRuleInstall { GxRoutingRuleInstallPresence presence; GxRoutingRuleDefinitionList routing_rule_definition; } GxRoutingRuleInstall; typedef struct gxEventChargingTimestampList { int32_t count; FdTime *list; } GxEventChargingTimestampList; typedef struct gxUnitValue { GxUnitValuePresence presence; int64_t value_digits; int32_t exponent; } GxUnitValue; typedef struct gxCcMoney { GxCcMoneyPresence presence; GxUnitValue unit_value; uint32_t currency_code; } GxCcMoney; typedef struct gxUsedServiceUnit { GxUsedServiceUnitPresence presence; int32_t reporting_reason; int32_t tariff_change_usage; uint32_t cc_time; GxCcMoney cc_money; uint64_t cc_total_octets; uint64_t cc_input_octets; uint64_t cc_output_octets; uint64_t cc_service_specific_units; GxEventChargingTimestampList event_charging_timestamp; } GxUsedServiceUnit; typedef struct gxUsedServiceUnitList { int32_t count; GxUsedServiceUnit *list; } GxUsedServiceUnitList; typedef struct gxGrantedServiceUnit { GxGrantedServiceUnitPresence presence; FdTime tariff_time_change; uint32_t cc_time; GxCcMoney cc_money; uint64_t cc_total_octets; uint64_t cc_input_octets; uint64_t cc_output_octets; uint64_t cc_service_specific_units; } GxGrantedServiceUnit; typedef struct gxGrantedServiceUnitList { int32_t count; GxGrantedServiceUnit *list; } GxGrantedServiceUnitList; typedef struct gxUsageMonitoringInformation { GxUsageMonitoringInformationPresence presence; GxMonitoringKeyOctetString monitoring_key; GxGrantedServiceUnitList granted_service_unit; GxUsedServiceUnitList used_service_unit; uint32_t quota_consumption_time; int32_t usage_monitoring_level; int32_t usage_monitoring_report; int32_t usage_monitoring_support; } GxUsageMonitoringInformation; typedef struct gxUsageMonitoringInformationList { int32_t count; GxUsageMonitoringInformation *list; } GxUsageMonitoringInformationList; typedef struct gxTunnelHeaderFilterList { int32_t count; GxTunnelHeaderFilterOctetString *list; } GxTunnelHeaderFilterList; typedef struct gxTunnelInformation { GxTunnelInformationPresence presence; uint32_t tunnel_header_length; GxTunnelHeaderFilterList tunnel_header_filter; } GxTunnelInformation; typedef struct gxCoaInformation { GxCoaInformationPresence presence; GxTunnelInformation tunnel_information; FdAddress coa_ip_address; } GxCoaInformation; typedef struct gxCoaInformationList { int32_t count; GxCoaInformation *list; } GxCoaInformationList; typedef struct gxChargingRuleNameList { int32_t count; GxChargingRuleNameOctetString *list; } GxChargingRuleNameList; typedef struct gxChargingRuleBaseNameList { int32_t count; GxChargingRuleBaseNameOctetString *list; } GxChargingRuleBaseNameList; typedef struct gxAccessNetworkChargingIdentifierGx { GxAccessNetworkChargingIdentifierGxPresence presence; GxAccessNetworkChargingIdentifierValueOctetString access_network_charging_identifier_value; GxChargingRuleBaseNameList charging_rule_base_name; GxChargingRuleNameList charging_rule_name; int32_t ip_can_session_charging_scope; } GxAccessNetworkChargingIdentifierGx; typedef struct gxAccessNetworkChargingIdentifierGxList { int32_t count; GxAccessNetworkChargingIdentifierGx *list; } GxAccessNetworkChargingIdentifierGxList; typedef struct gxMbsfnArea { GxMbsfnAreaPresence presence; uint32_t mbsfn_area_id; uint32_t carrier_frequency; } GxMbsfnArea; typedef struct gxMbsfnAreaList { int32_t count; GxMbsfnArea *list; } GxMbsfnAreaList; typedef struct gxMdtAllowedPlmnIdList { int32_t count; GxMdtAllowedPlmnIdOctetString *list; } GxMdtAllowedPlmnIdList; typedef struct gxTrackingAreaIdentityList { int32_t count; GxTrackingAreaIdentityOctetString *list; } GxTrackingAreaIdentityList; typedef struct gxLocationAreaIdentityList { int32_t count; GxLocationAreaIdentityOctetString *list; } GxLocationAreaIdentityList; typedef struct gxRoutingAreaIdentityList { int32_t count; GxRoutingAreaIdentityOctetString *list; } GxRoutingAreaIdentityList; typedef struct gxEUtranCellGlobalIdentityList { int32_t count; GxEUtranCellGlobalIdentityOctetString *list; } GxEUtranCellGlobalIdentityList; typedef struct gxCellGlobalIdentityList { int32_t count; GxCellGlobalIdentityOctetString *list; } GxCellGlobalIdentityList; typedef struct gxAreaScope { GxAreaScopePresence presence; GxCellGlobalIdentityList cell_global_identity; GxEUtranCellGlobalIdentityList e_utran_cell_global_identity; GxRoutingAreaIdentityList routing_area_identity; GxLocationAreaIdentityList location_area_identity; GxTrackingAreaIdentityList tracking_area_identity; } GxAreaScope; typedef struct gxMdtConfiguration { GxMdtConfigurationPresence presence; int32_t job_type; GxAreaScope area_scope; uint32_t list_of_measurements; uint32_t reporting_trigger; int32_t report_interval; int32_t report_amount; uint32_t event_threshold_rsrp; uint32_t event_threshold_rsrq; int32_t logging_interval; int32_t logging_duration; int32_t measurement_period_lte; int32_t measurement_period_umts; int32_t collection_period_rrm_lte; int32_t collection_period_rrm_umts; GxPositioningMethodOctetString positioning_method; GxMeasurementQuantityOctetString measurement_quantity; int32_t event_threshold_event_1f; int32_t event_threshold_event_1i; GxMdtAllowedPlmnIdList mdt_allowed_plmn_id; GxMbsfnAreaList mbsfn_area; } GxMdtConfiguration; typedef struct gxTraceData { GxTraceDataPresence presence; GxTraceReferenceOctetString trace_reference; int32_t trace_depth; GxTraceNeTypeListOctetString trace_ne_type_list; GxTraceInterfaceListOctetString trace_interface_list; GxTraceEventListOctetString trace_event_list; GxOmcIdOctetString omc_id; FdAddress trace_collection_entity; GxMdtConfiguration mdt_configuration; } GxTraceData; typedef struct gxAnGwAddressList { int32_t count; FdAddress *list; } GxAnGwAddressList; typedef struct gxUserCsgInformation { GxUserCsgInformationPresence presence; uint32_t csg_id; int32_t csg_access_mode; int32_t csg_membership_indication; } GxUserCsgInformation; typedef struct gxEventTriggerList { int32_t count; int32_t *list; } GxEventTriggerList; typedef struct gxEventReportIndication { GxEventReportIndicationPresence presence; int32_t an_trusted; GxEventTriggerList event_trigger; GxUserCsgInformation user_csg_information; int32_t ip_can_type; GxAnGwAddressList an_gw_address; Gx3gppSgsnAddressOctetString tgpp_sgsn_address; Gx3gppSgsnIpv6AddressOctetString tgpp_sgsn_ipv6_address; Gx3gppSgsnMccMncOctetString tgpp_sgsn_mcc_mnc; GxFramedIpAddressOctetString framed_ip_address; int32_t rat_type; GxRaiOctetString rai; Gx3gppUserLocationInfoOctetString tgpp_user_location_info; GxTraceData trace_data; GxTraceReferenceOctetString trace_reference; Gx3gpp2BsidOctetString tgpp2_bsid; Gx3gppMsTimezoneOctetString tgpp_ms_timezone; FdAddress routing_ip_address; FdAddress ue_local_ip_address; FdAddress henb_local_ip_address; uint32_t udp_source_port; GxPresenceReportingAreaInformation presence_reporting_area_information; } GxEventReportIndication; typedef struct gxFlowInformation { GxFlowInformationPresence presence; GxFlowDescriptionOctetString flow_description; GxPacketFilterIdentifierOctetString packet_filter_identifier; int32_t packet_filter_usage; GxTosTrafficClassOctetString tos_traffic_class; GxSecurityParameterIndexOctetString security_parameter_index; GxFlowLabelOctetString flow_label; int32_t flow_direction; GxRoutingRuleIdentifierOctetString routing_rule_identifier; } GxFlowInformation; typedef struct gxFlowInformationList { int32_t count; GxFlowInformation *list; } GxFlowInformationList; typedef struct gxApplicationDetectionInformation { GxApplicationDetectionInformationPresence presence; GxTdfApplicationIdentifierOctetString tdf_application_identifier; GxTdfApplicationInstanceIdentifierOctetString tdf_application_instance_identifier; GxFlowInformationList flow_information; } GxApplicationDetectionInformation; typedef struct gxApplicationDetectionInformationList { int32_t count; GxApplicationDetectionInformation *list; } GxApplicationDetectionInformationList; typedef struct gxContentVersionList { int32_t count; uint64_t *list; } GxContentVersionList; typedef struct gxRanNasReleaseCauseList { int32_t count; GxRanNasReleaseCauseOctetString *list; } GxRanNasReleaseCauseList; typedef struct gxRedirectServer { GxRedirectServerPresence presence; int32_t redirect_address_type; GxRedirectServerAddressOctetString redirect_server_address; } GxRedirectServer; typedef struct gxFilterIdList { int32_t count; GxFilterIdOctetString *list; } GxFilterIdList; typedef struct gxRestrictionFilterRuleList { int32_t count; GxRestrictionFilterRuleOctetString *list; } GxRestrictionFilterRuleList; typedef struct gxFinalUnitIndication { GxFinalUnitIndicationPresence presence; int32_t final_unit_action; GxRestrictionFilterRuleList restriction_filter_rule; GxFilterIdList filter_id; GxRedirectServer redirect_server; } GxFinalUnitIndication; typedef struct gxChargingRuleReport { GxChargingRuleReportPresence presence; GxChargingRuleNameList charging_rule_name; GxChargingRuleBaseNameList charging_rule_base_name; GxBearerIdentifierOctetString bearer_identifier; int32_t pcc_rule_status; int32_t rule_failure_code; GxFinalUnitIndication final_unit_indication; GxRanNasReleaseCauseList ran_nas_release_cause; GxContentVersionList content_version; } GxChargingRuleReport; typedef struct gxChargingRuleReportList { int32_t count; GxChargingRuleReport *list; } GxChargingRuleReportList; typedef struct gxTftPacketFilterInformation { GxTftPacketFilterInformationPresence presence; uint32_t precedence; GxTftFilterOctetString tft_filter; GxTosTrafficClassOctetString tos_traffic_class; GxSecurityParameterIndexOctetString security_parameter_index; GxFlowLabelOctetString flow_label; int32_t flow_direction; } GxTftPacketFilterInformation; typedef struct gxTftPacketFilterInformationList { int32_t count; GxTftPacketFilterInformation *list; } GxTftPacketFilterInformationList; typedef struct gxFixedUserLocationInfo { GxFixedUserLocationInfoPresence presence; GxSsidOctetString ssid; GxBssidOctetString bssid; GxLogicalAccessIdOctetString logical_access_id; GxPhysicalAccessIdOctetString physical_access_id; } GxFixedUserLocationInfo; typedef struct gxDefaultQosInformation { GxDefaultQosInformationPresence presence; int32_t qos_class_identifier; uint32_t max_requested_bandwidth_ul; uint32_t max_requested_bandwidth_dl; GxDefaultQosNameOctetString default_qos_name; } GxDefaultQosInformation; typedef struct gxAllocationRetentionPriority { GxAllocationRetentionPriorityPresence presence; uint32_t priority_level; int32_t pre_emption_capability; int32_t pre_emption_vulnerability; } GxAllocationRetentionPriority; typedef struct gxDefaultEpsBearerQos { GxDefaultEpsBearerQosPresence presence; int32_t qos_class_identifier; GxAllocationRetentionPriority allocation_retention_priority; } GxDefaultEpsBearerQos; typedef struct gxRatTypeList { int32_t count; int32_t *list; } GxRatTypeList; typedef struct gxIpCanTypeList { int32_t count; int32_t *list; } GxIpCanTypeList; typedef struct gxConditionalApnAggregateMaxBitrate { GxConditionalApnAggregateMaxBitratePresence presence; uint32_t apn_aggregate_max_bitrate_ul; uint32_t apn_aggregate_max_bitrate_dl; uint32_t extended_apn_ambr_ul; uint32_t extended_apn_ambr_dl; GxIpCanTypeList ip_can_type; GxRatTypeList rat_type; } GxConditionalApnAggregateMaxBitrate; typedef struct gxConditionalApnAggregateMaxBitrateList { int32_t count; GxConditionalApnAggregateMaxBitrate *list; } GxConditionalApnAggregateMaxBitrateList; typedef struct gxQosInformation { GxQosInformationPresence presence; int32_t qos_class_identifier; uint32_t max_requested_bandwidth_ul; uint32_t max_requested_bandwidth_dl; uint32_t extended_max_requested_bw_ul; uint32_t extended_max_requested_bw_dl; uint32_t guaranteed_bitrate_ul; uint32_t guaranteed_bitrate_dl; uint32_t extended_gbr_ul; uint32_t extended_gbr_dl; GxBearerIdentifierOctetString bearer_identifier; GxAllocationRetentionPriority allocation_retention_priority; uint32_t apn_aggregate_max_bitrate_ul; uint32_t apn_aggregate_max_bitrate_dl; uint32_t extended_apn_ambr_ul; uint32_t extended_apn_ambr_dl; GxConditionalApnAggregateMaxBitrateList conditional_apn_aggregate_max_bitrate; } GxQosInformation; typedef struct gxUserEquipmentInfo { GxUserEquipmentInfoPresence presence; int32_t user_equipment_info_type; GxUserEquipmentInfoValueOctetString user_equipment_info_value; } GxUserEquipmentInfo; typedef struct gxPacketFilterInformation { GxPacketFilterInformationPresence presence; GxPacketFilterIdentifierOctetString packet_filter_identifier; uint32_t precedence; GxPacketFilterContentOctetString packet_filter_content; GxTosTrafficClassOctetString tos_traffic_class; GxSecurityParameterIndexOctetString security_parameter_index; GxFlowLabelOctetString flow_label; int32_t flow_direction; } GxPacketFilterInformation; typedef struct gxPacketFilterInformationList { int32_t count; GxPacketFilterInformation *list; } GxPacketFilterInformationList; typedef struct gxTdfInformation { GxTdfInformationPresence presence; GxTdfDestinationRealmOctetString tdf_destination_realm; GxTdfDestinationHostOctetString tdf_destination_host; FdAddress tdf_ip_address; } GxTdfInformation; typedef struct gxSupportedFeatures { GxSupportedFeaturesPresence presence; uint32_t vendor_id; uint32_t feature_list_id; uint32_t feature_list; } GxSupportedFeatures; typedef struct gxSupportedFeaturesList { int32_t count; GxSupportedFeatures *list; } GxSupportedFeaturesList; typedef struct gxOcSupportedFeatures { GxOcSupportedFeaturesPresence presence; uint64_t oc_feature_vector; } GxOcSupportedFeatures; typedef struct gxSubscriptionId { GxSubscriptionIdPresence presence; int32_t subscription_id_type; GxSubscriptionIdDataOctetString subscription_id_data; } GxSubscriptionId; typedef struct gxSubscriptionIdList { int32_t count; GxSubscriptionId *list; } GxSubscriptionIdList; typedef struct gxCCR { GxCcrPresence presence; GxSessionIdOctetString session_id; int32_t drmp; uint32_t auth_application_id; GxOriginHostOctetString origin_host; GxOriginRealmOctetString origin_realm; GxDestinationRealmOctetString destination_realm; GxServiceContextIdOctetString service_context_id; int32_t cc_request_type; uint32_t cc_request_number; uint32_t credit_management_status; GxDestinationHostOctetString destination_host; uint32_t origin_state_id; GxSubscriptionIdList subscription_id; GxOcSupportedFeatures oc_supported_features; GxSupportedFeaturesList supported_features; GxTdfInformation tdf_information; int32_t network_request_support; GxPacketFilterInformationList packet_filter_information; int32_t packet_filter_operation; GxBearerIdentifierOctetString bearer_identifier; int32_t bearer_operation; int32_t dynamic_address_flag; int32_t dynamic_address_flag_extension; uint32_t pdn_connection_charging_id; GxFramedIpAddressOctetString framed_ip_address; GxFramedIpv6PrefixOctetString framed_ipv6_prefix; int32_t ip_can_type; Gx3gppRatTypeOctetString tgpp_rat_type; int32_t an_trusted; int32_t rat_type; int32_t termination_cause; GxUserEquipmentInfo user_equipment_info; GxQosInformation qos_information; int32_t qos_negotiation; int32_t qos_upgrade; GxDefaultEpsBearerQos default_eps_bearer_qos; GxDefaultQosInformation default_qos_information; GxAnGwAddressList an_gw_address; int32_t an_gw_status; Gx3gppSgsnMccMncOctetString tgpp_sgsn_mcc_mnc; Gx3gppSgsnAddressOctetString tgpp_sgsn_address; Gx3gppSgsnIpv6AddressOctetString tgpp_sgsn_ipv6_address; Gx3gppGgsnAddressOctetString tgpp_ggsn_address; Gx3gppGgsnIpv6AddressOctetString tgpp_ggsn_ipv6_address; Gx3gppSelectionModeOctetString tgpp_selection_mode; GxRaiOctetString rai; Gx3gppUserLocationInfoOctetString tgpp_user_location_info; GxFixedUserLocationInfo fixed_user_location_info; FdTime user_location_info_time; GxUserCsgInformation user_csg_information; GxTwanIdentifierOctetString twan_identifier; Gx3gppMsTimezoneOctetString tgpp_ms_timezone; GxRanNasReleaseCauseList ran_nas_release_cause; Gx3gppChargingCharacteristicsOctetString tgpp_charging_characteristics; GxCalledStationIdOctetString called_station_id; GxPdnConnectionIdOctetString pdn_connection_id; int32_t bearer_usage; int32_t online; int32_t offline; GxTftPacketFilterInformationList tft_packet_filter_information; GxChargingRuleReportList charging_rule_report; GxApplicationDetectionInformationList application_detection_information; GxEventTriggerList event_trigger; GxEventReportIndication event_report_indication; FdAddress access_network_charging_address; GxAccessNetworkChargingIdentifierGxList access_network_charging_identifier_gx; GxCoaInformationList coa_information; GxUsageMonitoringInformationList usage_monitoring_information; int32_t nbifom_support; int32_t nbifom_mode; int32_t default_access; uint64_t origination_time_stamp; uint32_t maximum_wait_time; uint32_t access_availability_change_reason; GxRoutingRuleInstall routing_rule_install; GxRoutingRuleRemove routing_rule_remove; FdAddress henb_local_ip_address; FdAddress ue_local_ip_address; uint32_t udp_source_port; uint32_t tcp_source_port; GxPresenceReportingAreaInformationList presence_reporting_area_information; GxLogicalAccessIdOctetString logical_access_id; GxPhysicalAccessIdOctetString physical_access_id; GxProxyInfoList proxy_info; GxRouteRecordList route_record; int32_t tgpp_ps_data_off_status; } GxCCR; typedef struct gxLoad { GxLoadPresence presence; int32_t load_type; uint64_t load_value; GxSourceidOctetString sourceid; } GxLoad; typedef struct gxLoadList { int32_t count; GxLoad *list; } GxLoadList; typedef struct gxFailedAvp { GxFailedAvpPresence presence; } GxFailedAvp; typedef struct gxConditionalPolicyInformation { GxConditionalPolicyInformationPresence presence; FdTime execution_time; GxDefaultEpsBearerQos default_eps_bearer_qos; uint32_t apn_aggregate_max_bitrate_ul; uint32_t apn_aggregate_max_bitrate_dl; uint32_t extended_apn_ambr_ul; uint32_t extended_apn_ambr_dl; GxConditionalApnAggregateMaxBitrateList conditional_apn_aggregate_max_bitrate; } GxConditionalPolicyInformation; typedef struct gxConditionalPolicyInformationList { int32_t count; GxConditionalPolicyInformation *list; } GxConditionalPolicyInformationList; typedef struct gxRoutingRuleReport { GxRoutingRuleReportPresence presence; GxRoutingRuleIdentifierList routing_rule_identifier; int32_t pcc_rule_status; uint32_t routing_rule_failure_code; } GxRoutingRuleReport; typedef struct gxRoutingRuleReportList { int32_t count; GxRoutingRuleReport *list; } GxRoutingRuleReportList; typedef struct gxPresenceReportingAreaIdentifierList { int32_t count; GxPresenceReportingAreaIdentifierOctetString *list; } GxPresenceReportingAreaIdentifierList; typedef struct gxPraRemove { GxPraRemovePresence presence; GxPresenceReportingAreaIdentifierList presence_reporting_area_identifier; } GxPraRemove; typedef struct gxPraInstall { GxPraInstallPresence presence; GxPresenceReportingAreaInformationList presence_reporting_area_information; } GxPraInstall; typedef struct gxCsgInformationReportingList { int32_t count; int32_t *list; } GxCsgInformationReportingList; typedef struct gxQosInformationList { int32_t count; GxQosInformation *list; } GxQosInformationList; typedef struct gxChargingInformation { GxChargingInformationPresence presence; GxPrimaryEventChargingFunctionNameOctetString primary_event_charging_function_name; GxSecondaryEventChargingFunctionNameOctetString secondary_event_charging_function_name; GxPrimaryChargingCollectionFunctionNameOctetString primary_charging_collection_function_name; GxSecondaryChargingCollectionFunctionNameOctetString secondary_charging_collection_function_name; } GxChargingInformation; typedef struct gxRequiredAccessInfoList { int32_t count; int32_t *list; } GxRequiredAccessInfoList; typedef struct gxRedirectInformation { GxRedirectInformationPresence presence; int32_t redirect_support; int32_t redirect_address_type; GxRedirectServerAddressOctetString redirect_server_address; } GxRedirectInformation; typedef struct gxFlowNumberList { int32_t count; uint32_t *list; } GxFlowNumberList; typedef struct gxFlows { GxFlowsPresence presence; uint32_t media_component_number; GxFlowNumberList flow_number; GxContentVersionList content_version; int32_t final_unit_action; uint32_t media_component_status; } GxFlows; typedef struct gxFlowsList { int32_t count; GxFlows *list; } GxFlowsList; typedef struct gxChargingRuleDefinition { GxChargingRuleDefinitionPresence presence; GxChargingRuleNameOctetString charging_rule_name; uint32_t service_identifier; uint32_t rating_group; GxFlowInformationList flow_information; int32_t default_bearer_indication; GxTdfApplicationIdentifierOctetString tdf_application_identifier; int32_t flow_status; GxQosInformation qos_information; int32_t ps_to_cs_session_continuity; int32_t reporting_level; int32_t online; int32_t offline; float max_plr_dl; float max_plr_ul; int32_t metering_method; uint32_t precedence; GxAfChargingIdentifierOctetString af_charging_identifier; GxFlowsList flows; GxMonitoringKeyOctetString monitoring_key; GxRedirectInformation redirect_information; int32_t mute_notification; int32_t af_signalling_protocol; GxSponsorIdentityOctetString sponsor_identity; GxApplicationServiceProviderIdentityOctetString application_service_provider_identity; GxRequiredAccessInfoList required_access_info; uint32_t sharing_key_dl; uint32_t sharing_key_ul; GxTrafficSteeringPolicyIdentifierDlOctetString traffic_steering_policy_identifier_dl; GxTrafficSteeringPolicyIdentifierUlOctetString traffic_steering_policy_identifier_ul; uint64_t content_version; } GxChargingRuleDefinition; typedef struct gxChargingRuleDefinitionList { int32_t count; GxChargingRuleDefinition *list; } GxChargingRuleDefinitionList; typedef struct gxChargingRuleInstall { GxChargingRuleInstallPresence presence; GxChargingRuleDefinitionList charging_rule_definition; GxChargingRuleNameList charging_rule_name; GxChargingRuleBaseNameList charging_rule_base_name; GxBearerIdentifierOctetString bearer_identifier; uint32_t monitoring_flags; FdTime rule_activation_time; FdTime rule_deactivation_time; int32_t resource_allocation_notification; int32_t charging_correlation_indicator; int32_t ip_can_type; } GxChargingRuleInstall; typedef struct gxChargingRuleInstallList { int32_t count; GxChargingRuleInstall *list; } GxChargingRuleInstallList; typedef struct gxChargingRuleRemove { GxChargingRuleRemovePresence presence; GxChargingRuleNameList charging_rule_name; GxChargingRuleBaseNameList charging_rule_base_name; GxRequiredAccessInfoList required_access_info; int32_t resource_release_notification; } GxChargingRuleRemove; typedef struct gxChargingRuleRemoveList { int32_t count; GxChargingRuleRemove *list; } GxChargingRuleRemoveList; typedef struct gxRedirectHostList { int32_t count; GxRedirectHostOctetString *list; } GxRedirectHostList; typedef struct gxOcOlr { GxOcOlrPresence presence; uint64_t oc_sequence_number; int32_t oc_report_type; uint32_t oc_reduction_percentage; uint32_t oc_validity_duration; } GxOcOlr; typedef struct gxExperimentalResult { GxExperimentalResultPresence presence; uint32_t vendor_id; uint32_t experimental_result_code; } GxExperimentalResult; typedef struct gxCCA { GxCcaPresence presence; GxSessionIdOctetString session_id; int32_t drmp; uint32_t auth_application_id; GxOriginHostOctetString origin_host; GxOriginRealmOctetString origin_realm; uint32_t result_code; GxExperimentalResult experimental_result; int32_t cc_request_type; uint32_t cc_request_number; GxOcSupportedFeatures oc_supported_features; GxOcOlr oc_olr; GxSupportedFeaturesList supported_features; int32_t bearer_control_mode; GxEventTriggerList event_trigger; GxEventReportIndication event_report_indication; uint32_t origin_state_id; GxRedirectHostList redirect_host; int32_t redirect_host_usage; uint32_t redirect_max_cache_time; GxChargingRuleRemoveList charging_rule_remove; GxChargingRuleInstallList charging_rule_install; GxChargingInformation charging_information; int32_t online; int32_t offline; GxQosInformationList qos_information; FdTime revalidation_time; GxDefaultEpsBearerQos default_eps_bearer_qos; GxDefaultQosInformation default_qos_information; int32_t bearer_usage; GxUsageMonitoringInformationList usage_monitoring_information; GxCsgInformationReportingList csg_information_reporting; GxUserCsgInformation user_csg_information; GxPraInstall pra_install; GxPraRemove pra_remove; GxPresenceReportingAreaInformation presence_reporting_area_information; int32_t session_release_cause; int32_t nbifom_support; int32_t nbifom_mode; int32_t default_access; uint32_t ran_rule_support; GxRoutingRuleReportList routing_rule_report; GxConditionalPolicyInformationList conditional_policy_information; int32_t removal_of_access; int32_t ip_can_type; GxErrorMessageOctetString error_message; GxErrorReportingHostOctetString error_reporting_host; GxFailedAvp failed_avp; GxProxyInfoList proxy_info; GxRouteRecordList route_record; GxLoadList load; } GxCCA; typedef struct gxRAA { GxRaaPresence presence; GxSessionIdOctetString session_id; int32_t drmp; GxOriginHostOctetString origin_host; GxOriginRealmOctetString origin_realm; uint32_t result_code; GxExperimentalResult experimental_result; uint32_t origin_state_id; GxOcSupportedFeatures oc_supported_features; GxOcOlr oc_olr; int32_t ip_can_type; int32_t rat_type; int32_t an_trusted; GxAnGwAddressList an_gw_address; Gx3gppSgsnMccMncOctetString tgpp_sgsn_mcc_mnc; Gx3gppSgsnAddressOctetString tgpp_sgsn_address; Gx3gppSgsnIpv6AddressOctetString tgpp_sgsn_ipv6_address; GxRaiOctetString rai; Gx3gppUserLocationInfoOctetString tgpp_user_location_info; FdTime user_location_info_time; uint32_t netloc_access_support; GxUserCsgInformation user_csg_information; Gx3gppMsTimezoneOctetString tgpp_ms_timezone; GxDefaultQosInformation default_qos_information; GxChargingRuleReportList charging_rule_report; GxErrorMessageOctetString error_message; GxErrorReportingHostOctetString error_reporting_host; GxFailedAvp failed_avp; GxProxyInfoList proxy_info; } GxRAA; typedef struct gxRAR { GxRarPresence presence; GxSessionIdOctetString session_id; int32_t drmp; uint32_t auth_application_id; GxOriginHostOctetString origin_host; GxOriginRealmOctetString origin_realm; GxDestinationRealmOctetString destination_realm; GxDestinationHostOctetString destination_host; int32_t re_auth_request_type; int32_t session_release_cause; uint32_t origin_state_id; GxOcSupportedFeatures oc_supported_features; GxEventTriggerList event_trigger; GxEventReportIndication event_report_indication; GxChargingRuleRemoveList charging_rule_remove; GxChargingRuleInstallList charging_rule_install; GxDefaultEpsBearerQos default_eps_bearer_qos; GxQosInformationList qos_information; GxDefaultQosInformation default_qos_information; FdTime revalidation_time; GxUsageMonitoringInformationList usage_monitoring_information; uint32_t pcscf_restoration_indication; GxConditionalPolicyInformationList conditional_policy_information; int32_t removal_of_access; int32_t ip_can_type; GxPraInstall pra_install; GxPraRemove pra_remove; GxCsgInformationReportingList csg_information_reporting; GxProxyInfoList proxy_info; GxRouteRecordList route_record; } GxRAR; #ifdef __cplusplus } #endif #endif /* __GX_STRUCT_H__ */
nikhilc149/e-utran-features-bug-fixes
cp/gtpv2c_set_ie.c
<filename>cp/gtpv2c_set_ie.c /* * Copyright (c) 2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtp_ies.h" #include "sm_struct.h" #include "gtpv2c_set_ie.h" #include "packet_filters.h" #include "gw_adapter.h" extern int clSystemLog; /** * @brief : helper function to get the location of the next information element '*ie' * that the buffer located at '*header' may be used, in the case that the size * of the information element IS known ahead of time * @param : header, header pre-populated that contains transmission buffer for message * @param : type, information element type value as defined in 3gpp 29.274 table 8.1-1 * @param : instance, Information element instance as specified by 3gpp 29.274 clause 6.1.3 * @param : length, size of information element created in message * @return : information element to be populated */ static gtpv2c_ie * set_next_ie(gtpv2c_header_t *header, uint8_t type, enum ie_instance instance, uint16_t length) { gtpv2c_ie *ie = (gtpv2c_ie *) (((uint8_t *) &header->teid) + ntohs(header->gtpc.message_len)); if (ntohs(header->gtpc.message_len) + length + sizeof(gtpv2c_ie) > MAX_GTPV2C_LENGTH) { rte_panic("Insufficient space in UDP buffer for IE\n"); } header->gtpc.message_len = htons( ntohs(header->gtpc.message_len) + length + sizeof(gtpv2c_ie)); ie->type = type; ie->instance = instance; ie->length = htons(length); ie->spare = 0; return ie; } /** * @brief : helper function to get the location of the next information element '*ie' * that the buffer located at '*header' may be used, in the case that the size * of the information element IS NOT known ahead of time * @param : header, header pre-populated that contains transmission buffer for message * @param : type, information element type value as defined in 3gpp 29.274 table 8.1-1 * @param : instance, Information element instance as specified by 3gpp 29.274 clause 6.1.3 * @return : information element to be populated */ static gtpv2c_ie * set_next_unsized_ie(gtpv2c_header_t *header, uint8_t type, enum ie_instance instance) { gtpv2c_ie *ie = (gtpv2c_ie *) (((uint8_t *) &header->teid) + ntohs(header->gtpc.message_len)); ie->type = type; ie->instance = instance; ie->spare = 0; return ie; } /** * @brief : helper function to update the size of a gtp message header field within the * transmit buffer *header by the length of 'length' due to the length of the * information element 'ie' * @param : header, header pre-populated that contains transmission buffer for message * @param : ie, information element to be added to gtp message buffer * @param : length, size of information element created in message */ static void set_ie_size(gtpv2c_header_t *header, gtpv2c_ie *ie, uint16_t length) { if (ntohs(header->gtpc.message_len) + length + sizeof(gtpv2c_ie) > MAX_GTPV2C_LENGTH) { rte_panic("Insufficient space in UDP buffer for IE\n"); } ie->length = htons(length); header->gtpc.message_len = htons( ntohs(header->gtpc.message_len) + length + sizeof(gtpv2c_ie)); } /** * @brief : helper function to get the information element length used to increment gtp * header length field * @param : ie, information element pointer * @return : size of information element created in message */ static inline uint16_t get_ie_return(gtpv2c_ie *ie) { return sizeof(gtpv2c_ie) + ntohs(ie->length); } /** * @brief : helper function to set general value within an inforation element of size 1 byte * @param : header, header pre-populated that contains transmission buffer for message * @param : type, information element type value as defined in 3gpp 29.274 table 8.1-1 * @param : instance, Information element instance as specified by 3gpp 29.274 clause 6.1.3 * @param : value, value of information element * @return : size of information element(return value of get_ie_return) */ static uint16_t set_uint8_ie(gtpv2c_header_t *header, uint8_t type, enum ie_instance instance, uint8_t value) { gtpv2c_ie *ie = set_next_ie(header, type, instance, sizeof(uint8_t)); uint8_t *value_ptr = IE_TYPE_PTR_FROM_GTPV2C_IE(uint8_t, ie); *value_ptr = value; return get_ie_return(ie); } /** * @brief : helper function to set general value within an information element of size 4 bytes * @param : header, header pre-populated that contains transmission buffer for message * @param : type, information element type value as defined in 3gpp 29.274 table 8.1-1 * @param : instance, Information element instance as specified by 3gpp 29.274 clause 6.1.3 * @param : value, value of information element * @return : size of information element(return value of get_ie_return) */ static uint16_t set_uint32_ie(gtpv2c_header_t *header, uint8_t type, enum ie_instance instance, uint8_t value) { gtpv2c_ie *ie = set_next_ie(header, type, instance, sizeof(uint32_t)); uint32_t *value_ptr = IE_TYPE_PTR_FROM_GTPV2C_IE(uint32_t, ie); *value_ptr = value; return get_ie_return(ie); } uint16_t set_ie_copy(gtpv2c_header_t *header, gtpv2c_ie *src_ie) { uint16_t len = ntohs(src_ie->length); gtpv2c_ie *ie = set_next_ie(header, src_ie->type, src_ie->instance, len); memcpy(((uint8_t *)ie)+sizeof(gtpv2c_ie),((uint8_t *)src_ie)+sizeof(gtpv2c_ie),len); return get_ie_return(ie); } /** * @brief : helper function to set ie header values * @param : header, ie header * @param : type, information element type value as defined in 3gpp 29.274 table 8.1-1 * @param : instance, Information element instance as specified by 3gpp 29.274 clause 6.1.3 * @param : length, size of information element created in message * @return : nothing */ void set_ie_header(ie_header_t *header, uint8_t type, enum ie_instance instance, uint16_t length) { header->type = type; header->instance = instance; header->len = length; } void set_cause_error_value(gtp_cause_ie_t *cause, enum ie_instance instance, uint8_t cause_value, uint8_t cause_source) { set_ie_header(&cause->header, GTP_IE_CAUSE, instance, sizeof(struct cause_ie_hdr_t)); cause->cause_value = cause_value; cause->pce = 0; cause->bce = 0; cause->spareinstance = 0; cause->cs = cause_source; } void set_cause_accepted(gtp_cause_ie_t *cause, enum ie_instance instance) { set_ie_header(&cause->header, GTP_IE_CAUSE, instance, sizeof(struct cause_ie_hdr_t)); cause->cause_value = GTPV2C_CAUSE_REQUEST_ACCEPTED; cause->pce = 0; cause->bce = 0; cause->cs = 0; cause->spareinstance = 0; } void set_csresp_cause(gtp_cause_ie_t *cause, uint8_t cause_value, enum ie_instance instance) { set_ie_header(&cause->header, GTP_IE_CAUSE, instance, sizeof(struct cause_ie_hdr_t)); cause->cause_value = cause_value; cause->pce = 0; cause->bce = 0; cause->cs = 0; cause->spareinstance = 0; } uint16_t set_ar_priority_ie(gtpv2c_header_t *header, enum ie_instance instance, eps_bearer *bearer) { gtpv2c_ie *ie = set_next_ie(header, GTP_IE_ALLOC_RETEN_PRIORITY, instance, sizeof(ar_priority_ie)); ar_priority_ie *ar_priority_ie_ptr = IE_TYPE_PTR_FROM_GTPV2C_IE(ar_priority_ie, ie); ar_priority_ie_ptr->preemption_vulnerability = bearer->qos.arp.preemption_vulnerability; ar_priority_ie_ptr->spare1 = 0; ar_priority_ie_ptr->priority_level = bearer->qos.arp.priority_level; ar_priority_ie_ptr->preemption_capability = bearer->qos.arp.preemption_capability; ar_priority_ie_ptr->spare2 = 0; return get_ie_return(ie); } int set_gtpc_fteid(gtp_fully_qual_tunn_endpt_idnt_ie_t *fteid, enum gtpv2c_interfaces interface, enum ie_instance instance, node_address_t node_value, uint32_t teid) { int size = sizeof(uint8_t); fteid->interface_type = interface; fteid->teid_gre_key = teid; size += sizeof(uint32_t); if (node_value.ip_type == PDN_IP_TYPE_IPV4) { size += sizeof(struct in_addr); fteid->v4 = PRESENT; fteid->ipv4_address = node_value.ipv4_addr; } else if (node_value.ip_type == PDN_IP_TYPE_IPV6) { size += sizeof(struct in6_addr); fteid->v6 = PRESENT; memcpy(fteid->ipv6_address, node_value.ipv6_addr, IPV6_ADDRESS_LEN); } else if (node_value.ip_type == PDN_IP_TYPE_IPV4V6) { size += sizeof(struct in_addr); size += sizeof(struct in6_addr); fteid->v4 = PRESENT; fteid->v6 = PRESENT; fteid->ipv4_address = node_value.ipv4_addr; memcpy(fteid->ipv6_address, node_value.ipv6_addr, IPV6_ADDRESS_LEN); } set_ie_header(&fteid->header, GTP_IE_FULLY_QUAL_TUNN_ENDPT_IDNT, instance, size); return size + IE_HEADER_SIZE; } uint16_t set_ipv4_fteid_ie(gtpv2c_header_t *header, enum gtpv2c_interfaces interface, enum ie_instance instance, struct in_addr ipv4, uint32_t teid) { gtpv2c_ie *ie = set_next_ie(header, GTP_IE_FULLY_QUAL_TUNN_ENDPT_IDNT, instance, sizeof(struct fteid_ie_hdr_t) + sizeof(struct in_addr)); fteid_ie *fteid_ie_ptr = IE_TYPE_PTR_FROM_GTPV2C_IE(fteid_ie, ie); fteid_ie_ptr->fteid_ie_hdr.v4 = 1; fteid_ie_ptr->fteid_ie_hdr.v6 = 0; fteid_ie_ptr->fteid_ie_hdr.interface_type = interface; fteid_ie_ptr->fteid_ie_hdr.teid_or_gre = teid; fteid_ie_ptr->ip_u.ipv4 = ipv4; return get_ie_return(ie); } void set_paa(gtp_pdn_addr_alloc_ie_t *paa, enum ie_instance instance, pdn_connection *pdn) { int size = sizeof(uint8_t); paa->spare2 = 0; if (pdn->pdn_type.ipv4) { size += sizeof(struct in_addr); paa->pdn_type = PDN_IP_TYPE_IPV4; paa->pdn_addr_and_pfx = pdn->uipaddr.ipv4.s_addr; } if (pdn->pdn_type.ipv6) { size += sizeof(uint8_t) + sizeof(struct in6_addr); paa->pdn_type = PDN_IP_TYPE_IPV6; paa->ipv6_prefix_len = pdn->prefix_len; memcpy(paa->paa_ipv6, pdn->uipaddr.ipv6.s6_addr, IPV6_ADDRESS_LEN); } if (pdn->pdn_type.ipv4 && pdn->pdn_type.ipv6) paa->pdn_type = PDN_IP_TYPE_IPV4V6; set_ie_header(&paa->header, GTP_IE_PDN_ADDR_ALLOC, instance, size); return; } uint16_t set_ipv4_paa_ie(gtpv2c_header_t *header, enum ie_instance instance, struct in_addr ipv4) { gtpv2c_ie *ie = set_next_ie(header, GTP_IE_PDN_ADDR_ALLOC, instance, sizeof(struct paa_ie_hdr_t) + sizeof(struct in_addr)); paa_ie *paa_ie_ptr = IE_TYPE_PTR_FROM_GTPV2C_IE(paa_ie, ie); paa_ie_ptr->paa_ie_hdr.pdn_type = PDN_IP_TYPE_IPV4; paa_ie_ptr->paa_ie_hdr.spare = 0; paa_ie_ptr->ip_type_union.ipv4 = ipv4; return get_ie_return(ie); } struct in_addr get_ipv4_paa_ipv4(gtpv2c_ie *ie) { paa_ie *paa_ie_ptr = IE_TYPE_PTR_FROM_GTPV2C_IE(paa_ie, ie); paa_ie_ptr->paa_ie_hdr.pdn_type = PDN_IP_TYPE_IPV4; paa_ie_ptr->paa_ie_hdr.spare = 0; return(paa_ie_ptr->ip_type_union.ipv4); } void set_apn_restriction(gtp_apn_restriction_ie_t *apn_restriction, enum ie_instance instance, uint8_t restriction_type) { set_ie_header(&apn_restriction->header, GTP_IE_APN_RESTRICTION, instance, sizeof(uint8_t)); apn_restriction->rstrct_type_val = restriction_type; return; } void set_change_reporting_action(gtp_chg_rptng_act_ie_t *chg_rptng_act, enum ie_instance instance, uint8_t action) { set_ie_header(&chg_rptng_act->header, GTP_IE_CHG_RPTNG_ACT, instance, sizeof(uint8_t)); chg_rptng_act->action = action; } uint16_t set_apn_restriction_ie(gtpv2c_header_t *header, enum ie_instance instance, uint8_t apn_restriction) { return set_uint8_ie(header, GTP_IE_APN_RESTRICTION, instance, apn_restriction); } void set_ebi(gtp_eps_bearer_id_ie_t *ebi, enum ie_instance instance, uint8_t eps_bearer_id) { set_ie_header(&ebi->header, GTP_IE_EPS_BEARER_ID, instance, sizeof(uint8_t)); ebi->ebi_ebi = eps_bearer_id; ebi->ebi_spare2 = 0; } void set_ar_priority(gtp_alloc_reten_priority_ie_t *arp, enum ie_instance instance, eps_bearer *bearer) { set_ie_header(&arp->header, GTP_IE_ALLOC_RETEN_PRIORITY, instance, sizeof(uint8_t)); arp->spare2 = 0; arp->pci = bearer->qos.arp.preemption_capability; arp->pl = bearer->qos.arp.priority_level; arp->pvi = bearer->qos.arp.preemption_vulnerability; arp->spare3 = 0; } /** * @brief : generate a packet filter identifier based on availabe for that bearer * @param : bearer, * to check the identifier availablity * @return : identifier between 1 to 16 for sucess and -1 for failure */ static int get_packet_filter_identifier(eps_bearer *bearer){ for(uint8_t i = 1; i <= MAX_FILTERS_PER_UE; i++ ){ if(bearer->packet_filter_map[i] == NOT_PRESENT){ bearer->packet_filter_map[i] = PRESENT; return i; } } return -1; } uint8_t set_bearer_tft(gtp_eps_bearer_lvl_traffic_flow_tmpl_ie_t *tft, enum ie_instance instance, uint8_t tft_op_code, eps_bearer *bearer, char *rule_name) { uint32_t mask; uint8_t i = 0; uint8_t length; uint8_t len_index = 0; uint8_t tft_op_code_index = 0; dynamic_rule_t *rule = NULL; uint8_t num_rule_filters = 0; uint8_t counter = 0; uint8_t num_dyn_rule = bearer->num_dynamic_filters; uint8_t num_prdef_rule = bearer->num_prdef_filters; num_rule_filters = num_dyn_rule + num_prdef_rule; tft_op_code_index = i; tft->eps_bearer_lvl_tft[i++] = tft_op_code; for(uint8_t iCnt = 0; iCnt < num_rule_filters; ++iCnt) { if(num_prdef_rule){ counter = bearer->num_prdef_filters - num_prdef_rule; rule = bearer->prdef_rules[counter]; num_prdef_rule--; }else if(num_dyn_rule){ counter = bearer->num_dynamic_filters - num_dyn_rule; rule = bearer->dynamic_rules[counter]; num_dyn_rule--; }else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT" No filters present in bearer \n", LOG_VALUE); return -1; } if(tft_op_code != TFT_CREATE_NEW && (rule_name != NULL && (strncmp(rule_name, rule->rule_name, RULE_NAME_LEN) != 0 ))){ continue; } for(int flow_cnt = 0; flow_cnt < rule->num_flw_desc; flow_cnt++) { length = 0; tft->eps_bearer_lvl_tft[tft_op_code_index] += 1; /*Store packet filter identifier in rule*/ if(rule->flow_desc[flow_cnt].sdf_flw_desc.direction && tft_op_code != TFT_REMOVE_FILTER_EXISTING) rule->flow_desc[flow_cnt].pckt_fltr_identifier = get_packet_filter_identifier(bearer); if(tft_op_code == TFT_REMOVE_FILTER_EXISTING){ tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].pckt_fltr_identifier; bearer->packet_filter_map[rule->flow_desc[flow_cnt].pckt_fltr_identifier] = NOT_PRESENT; continue; } if(TFT_DIRECTION_UPLINK_ONLY == rule->flow_desc[flow_cnt].sdf_flw_desc.direction) { tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].pckt_fltr_identifier + TFT_UPLINK; } else if(TFT_DIRECTION_DOWNLINK_ONLY == rule->flow_desc[flow_cnt].sdf_flw_desc.direction) { tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].pckt_fltr_identifier + TFT_DOWNLINK; } else if(TFT_DIRECTION_BIDIRECTIONAL == rule->flow_desc[flow_cnt].sdf_flw_desc.direction) { tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].pckt_fltr_identifier + TFT_BIDIRECTIONAL; } else { tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].pckt_fltr_identifier; } tft->eps_bearer_lvl_tft[i++] = rule->precedence; /* precedence */ len_index = i++; tft->eps_bearer_lvl_tft[i++] = TFT_PROTO_IDENTIFIER_NEXT_HEADER_TYPE; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.proto_id; length += 2; if(TFT_DIRECTION_DOWNLINK_ONLY == rule->flow_desc[flow_cnt].sdf_flw_desc.direction) { tft->eps_bearer_lvl_tft[i++] = TFT_SINGLE_REMOTE_PORT_TYPE; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.remote_port_low >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.remote_port_low & 0xff; length += 3; tft->eps_bearer_lvl_tft[i++] = TFT_SINGLE_SRC_PORT_TYPE; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.local_port_low >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.local_port_low & 0xff; length += 3; if (rule->flow_desc[flow_cnt].sdf_flw_desc.v4) { tft->eps_bearer_lvl_tft[i++] = TFT_IPV4_SRC_ADDR_TYPE; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip_addr.s_addr & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip_addr.s_addr >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip_addr.s_addr >> 16) & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip_addr.s_addr >> 24) & 0xff; length += 5; mask = 0xffffffff << (32 - rule->flow_desc[flow_cnt].sdf_flw_desc.local_ip_mask); tft->eps_bearer_lvl_tft[i++] = (mask >> 24) & 0xff; tft->eps_bearer_lvl_tft[i++] = (mask >> 16) & 0xff; tft->eps_bearer_lvl_tft[i++] = (mask >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = mask & 0xff; length += 4; } else if (rule->flow_desc[flow_cnt].sdf_flw_desc.v6) { tft->eps_bearer_lvl_tft[i++] = TFT_IPV6_SRC_ADDR_PREFIX_LEN_TYPE; for (int cnt = 0; cnt < IPV6_ADDRESS_LEN; cnt++) { tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip6_addr.s6_addr[cnt]; } length += IPV6_ADDRESS_LEN + 1; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.local_ip_mask; length += 1; } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Invalid IP address family type is set", "Cannot set Traffic Flow Template\n",LOG_VALUE); } if (rule->flow_desc[flow_cnt].sdf_flw_desc.v4) { tft->eps_bearer_lvl_tft[i++] = TFT_IPV4_REMOTE_ADDR_TYPE; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip_addr.s_addr & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip_addr.s_addr >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip_addr.s_addr >> 16) & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip_addr.s_addr >> 24) & 0xff; length += 5; mask = 0xffffffff << (32 - rule->flow_desc[flow_cnt].sdf_flw_desc.remote_ip_mask); tft->eps_bearer_lvl_tft[i++] = (mask >> 24) & 0xff; tft->eps_bearer_lvl_tft[i++] = (mask >> 16) & 0xff; tft->eps_bearer_lvl_tft[i++] = (mask >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = mask & 0xff; length += 4; } else if (rule->flow_desc[flow_cnt].sdf_flw_desc.v6) { tft->eps_bearer_lvl_tft[i++] = TFT_IPV6_REMOTE_ADDR_PREFIX_LEN_TYPE; for (int cnt = 0; cnt < IPV6_ADDRESS_LEN; cnt++) { tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip6_addr.s6_addr[cnt]; } length += IPV6_ADDRESS_LEN + 1; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.remote_ip_mask; length += 1; } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Invalid IP address family type is set", "Cannot set Traffic Flow Template\n",LOG_VALUE); } } else { tft->eps_bearer_lvl_tft[i++] = TFT_SINGLE_REMOTE_PORT_TYPE; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.local_port_low >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.local_port_low & 0xff; length += 3; tft->eps_bearer_lvl_tft[i++] = TFT_SINGLE_SRC_PORT_TYPE; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.remote_port_low >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.remote_port_low & 0xff; length += 3; if (rule->flow_desc[flow_cnt].sdf_flw_desc.v4) { tft->eps_bearer_lvl_tft[i++] = TFT_IPV4_SRC_ADDR_TYPE; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip_addr.s_addr & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip_addr.s_addr >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip_addr.s_addr >> 16) & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip_addr.s_addr >> 24) & 0xff; length += 5; mask = 0xffffffff << (32 - rule->flow_desc[flow_cnt].sdf_flw_desc.remote_ip_mask); tft->eps_bearer_lvl_tft[i++] = (mask >> 24) & 0xff; tft->eps_bearer_lvl_tft[i++] = (mask >> 16) & 0xff; tft->eps_bearer_lvl_tft[i++] = (mask >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = mask & 0xff; length += 4; } else if (rule->flow_desc[flow_cnt].sdf_flw_desc.v6) { tft->eps_bearer_lvl_tft[i++] = TFT_IPV6_SRC_ADDR_PREFIX_LEN_TYPE; for (int cnt = 0; cnt < IPV6_ADDRESS_LEN; cnt++) { tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.uremoteip.remote_ip6_addr.s6_addr[cnt]; } length += IPV6_ADDRESS_LEN + 1; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.remote_ip_mask; length += 1; } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Invalid IP address family type is set", "Cannot set Traffic Flow Template\n",LOG_VALUE); } if (rule->flow_desc[flow_cnt].sdf_flw_desc.v4) { tft->eps_bearer_lvl_tft[i++] = TFT_IPV4_REMOTE_ADDR_TYPE; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip_addr.s_addr & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip_addr.s_addr >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip_addr.s_addr >> 16) & 0xff; tft->eps_bearer_lvl_tft[i++] = (rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip_addr.s_addr >> 24) & 0xff; length += 5; mask = 0xffffffff << (32 - rule->flow_desc[flow_cnt].sdf_flw_desc.local_ip_mask); tft->eps_bearer_lvl_tft[i++] = (mask >> 24) & 0xff; tft->eps_bearer_lvl_tft[i++] = (mask >> 16) & 0xff; tft->eps_bearer_lvl_tft[i++] = (mask >> 8) & 0xff; tft->eps_bearer_lvl_tft[i++] = mask & 0xff; length += 4; } else if (rule->flow_desc[flow_cnt].sdf_flw_desc.v6) { tft->eps_bearer_lvl_tft[i++] = TFT_IPV6_REMOTE_ADDR_PREFIX_LEN_TYPE; for (int cnt = 0; cnt < IPV6_ADDRESS_LEN; cnt++) { tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.ulocalip.local_ip6_addr.s6_addr[cnt]; } length += IPV6_ADDRESS_LEN + 1; tft->eps_bearer_lvl_tft[i++] = rule->flow_desc[flow_cnt].sdf_flw_desc.local_ip_mask; length += 1; } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Invalid IP address family type is set", "Cannot set Traffic Flow Template\n",LOG_VALUE); } } tft->eps_bearer_lvl_tft[len_index] = length; /* length */ } } set_ie_header(&tft->header, GTP_IE_EPS_BEARER_LVL_TRAFFIC_FLOW_TMPL, instance, i); return (i + IE_HEADER_SIZE); } void set_pti(gtp_proc_trans_id_ie_t *pti, enum ie_instance instance, uint8_t proc_trans_id) { set_ie_header(&pti->header, GTP_IE_PROC_TRANS_ID, instance, sizeof(uint8_t)); pti->proc_trans_id = proc_trans_id; } uint16_t set_ebi_ie(gtpv2c_header_t *header, enum ie_instance instance, uint8_t ebi) { if (ebi & 0xF0) clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Invalid EBI used %"PRIu8"\n", LOG_VALUE, ebi); return set_uint8_ie(header, GTP_IE_EPS_BEARER_ID, instance, ebi); } uint16_t set_pti_ie(gtpv2c_header_t *header, enum ie_instance instance, uint8_t pti) { return set_uint8_ie(header, GTP_IE_PROC_TRANS_ID, instance, pti); } uint16_t set_charging_id_ie(gtpv2c_header_t *header, enum ie_instance instance, uint32_t charging_id) { return set_uint32_ie(header, GTP_IE_PROC_TRANS_ID, instance, charging_id); } void set_charging_id(gtp_charging_id_ie_t *charging_id, enum ie_instance instance, uint32_t chrgng_id_val) { set_ie_header(&charging_id->header, GTP_IE_CHARGING_ID, instance, sizeof(uint8_t)); charging_id->chrgng_id_val = chrgng_id_val; } void set_bearer_qos(gtp_bearer_qlty_of_svc_ie_t *bqos, enum ie_instance instance, eps_bearer *bearer) { set_ie_header(&bqos->header, GTP_IE_BEARER_QLTY_OF_SVC, instance, (sizeof(gtp_bearer_qlty_of_svc_ie_t) - IE_HEADER_SIZE)); bqos->spare2 = 0; bqos->pci = bearer->qos.arp.preemption_capability; bqos->pl = bearer->qos.arp.priority_level;; bqos->spare3 = 0; bqos->pvi = bearer->qos.arp.preemption_vulnerability; bqos->qci = bearer->qos.qci; bqos->max_bit_rate_uplnk = bearer->qos.ul_mbr; bqos->max_bit_rate_dnlnk = bearer->qos.dl_mbr; bqos->guarntd_bit_rate_uplnk = bearer->qos.ul_gbr; bqos->guarntd_bit_rate_dnlnk = bearer->qos.dl_gbr; } uint16_t set_bearer_qos_ie(gtpv2c_header_t *header, enum ie_instance instance, eps_bearer *bearer) { /* subtract 12 from size as MBR, GBR for uplink and downlink are * uint64_t but encoded in 5 bytes. */ gtpv2c_ie *ie = set_next_ie(header, GTP_IE_BEARER_QLTY_OF_SVC, instance, sizeof(bearer_qos_ie) - 12); bearer_qos_ie *bqos = IE_TYPE_PTR_FROM_GTPV2C_IE(bearer_qos_ie, ie); bqos->arp.preemption_vulnerability = bearer->qos.arp.preemption_vulnerability; bqos->arp.spare1 = 0; bqos->arp.priority_level = bearer->qos.arp.priority_level; bqos->arp.preemption_capability = bearer->qos.arp.preemption_capability; bqos->arp.spare2 = 0; /* VS: Need to remove following memcpy statement */ /* subtract 12 from size as MBR, GBR for uplink and downlink are * uint64_t but encoded in 5 bytes. */ /* memcpy(&bqos->qos, &bearer->qos.qos, sizeof(bqos->qos) - 12); */ /** * IE specific data segment for Quality of Service (QoS). * * Definition used by bearer_qos_ie and flow_qos_ie. */ bqos->qci = bearer->qos.qci; bqos->ul_mbr = bearer->qos.ul_mbr; bqos->dl_mbr = bearer->qos.dl_mbr; bqos->ul_gbr = bearer->qos.ul_gbr; bqos->dl_gbr = bearer->qos.dl_gbr; return get_ie_return(ie); } uint16_t set_bearer_tft_ie(gtpv2c_header_t *header, enum ie_instance instance, eps_bearer *bearer) { gtpv2c_ie *ie = set_next_unsized_ie(header, GTP_IE_EPS_BEARER_LVL_TRAFFIC_FLOW_TMPL, instance); bearer_tft_ie *tft = IE_TYPE_PTR_FROM_GTPV2C_IE(bearer_tft_ie, ie); create_pkt_filter *cpf = (create_pkt_filter *) &tft[1]; uint8_t i; uint16_t ie_length = 0; tft->num_pkt_filters = 0; tft->tft_op_code = TFT_OP_CREATE_NEW; tft->parameter_list = 0; for (i = 0; i < MAX_FILTERS_PER_UE; ++i) { if (bearer->packet_filter_map[i] == -ENOENT) continue; ++tft->num_pkt_filters; packet_filter *pf = get_packet_filter(bearer->packet_filter_map[i]); if (pf == NULL) continue; packet_filter_component *component = (packet_filter_component *) &cpf[1]; cpf->pkt_filter_id = i; cpf->direction = pf->pkt_fltr.direction; cpf->spare = 0; /*TODO : This param is removed from SDF. /Handle it appropriatly here.*/ /*cpf->precedence = pf->pkt_fltr.precedence;*/ cpf->precedence = 0; cpf->pkt_filter_length = 0; if (pf->pkt_fltr.remote_ip_mask != 0) { component->type = IPV4_REMOTE_ADDRESS; component->type_union.ipv4.ipv4 = pf->pkt_fltr.remote_ip_addr; component->type_union.ipv4.mask.s_addr = UINT32_MAX >> (32 - pf->pkt_fltr.remote_ip_mask); component = (packet_filter_component *) &component->type_union.ipv4.next_component; cpf->pkt_filter_length += sizeof(component->type_union.ipv4); } if (pf->pkt_fltr.local_ip_mask != 0) { component->type = IPV4_LOCAL_ADDRESS; component->type_union.ipv4.ipv4 = pf->pkt_fltr.local_ip_addr; component->type_union.ipv4.mask.s_addr = UINT32_MAX >> (32 - pf->pkt_fltr.local_ip_mask); component = (packet_filter_component *) &component->type_union.ipv4.next_component; cpf->pkt_filter_length += sizeof(component->type_union.ipv4); } if (pf->pkt_fltr.proto_mask != 0) { component->type = PROTOCOL_ID_NEXT_HEADER; component->type_union.proto.proto = pf->pkt_fltr.proto; component = (packet_filter_component *) &component->type_union.proto.next_component; cpf->pkt_filter_length += sizeof(component->type_union.proto); } if (pf->pkt_fltr.remote_port_low == pf->pkt_fltr.remote_port_high) { component->type = SINGLE_REMOTE_PORT; component->type_union.port.port = pf->pkt_fltr.remote_port_low; component = (packet_filter_component *) &component->type_union.port.next_component; cpf->pkt_filter_length += sizeof(component->type_union.port); } else if (pf->pkt_fltr.remote_port_low != 0 || pf->pkt_fltr.remote_port_high != UINT16_MAX) { component->type = REMOTE_PORT_RANGE; component->type_union.port_range.port_low = pf->pkt_fltr.remote_port_low; component->type_union.port_range.port_high = pf->pkt_fltr.remote_port_high; component = (packet_filter_component *) &component->type_union.port_range.next_component; cpf->pkt_filter_length += sizeof(component->type_union.port_range); } if (pf->pkt_fltr.local_port_low == pf->pkt_fltr.local_port_high) { component->type = SINGLE_LOCAL_PORT; component->type_union.port.port = pf->pkt_fltr.local_port_low; component = (packet_filter_component *) &component->type_union.port.next_component; cpf->pkt_filter_length += sizeof(component->type_union.port); } else if (pf->pkt_fltr.local_port_low != 0 || pf->pkt_fltr.local_port_high != UINT16_MAX) { component->type = LOCAL_PORT_RANGE; component->type_union.port_range.port_low = pf->pkt_fltr.local_port_low; component->type_union.port_range.port_high = pf->pkt_fltr.local_port_high; component = (packet_filter_component *) &component->type_union.port_range.next_component; cpf->pkt_filter_length += sizeof(component->type_union.port_range); } ie_length += cpf->pkt_filter_length + sizeof(create_pkt_filter); cpf = (create_pkt_filter *) component; } set_ie_size(header, ie, sizeof(bearer_tft_ie) + ie_length); return get_ie_return(ie); } uint16_t set_recovery_ie(gtpv2c_header_t *header, enum ie_instance instance) { /** TODO: According to 3gpp TS 29.274 [7.1.1] and 23.007 [16.1.1 * Restoration Procedures] this value (currently using 0) *should* * be obtained at SPGW startup, from a local non-volatile counter * (modulo 256) which is denoted as the 'local Restart Counter'. * Instead we set this value as 0 */ #ifdef USE_REST /* Support for restart counter */ return set_uint8_ie(header, GTP_IE_RECOVERY, instance, rstCnt); #else return set_uint8_ie(header, GTP_IE_RECOVERY, instance, 0); #endif /* USE_REST */ } void add_grouped_ie_length(gtpv2c_ie *group_ie, uint16_t grouped_ie_length) { group_ie->length = htons(ntohs(group_ie->length) + grouped_ie_length); } gtpv2c_ie * create_bearer_context_ie(gtpv2c_header_t *header, enum ie_instance instance) { return set_next_ie(header, GTP_IE_BEARER_CONTEXT, instance, 0); } void set_fqdn_ie(gtpv2c_header_t *header, char *fqdn) { gtpv2c_ie *ie = set_next_ie(header, GTP_IE_FULLY_QUAL_DOMAIN_NAME, IE_INSTANCE_ZERO, strnlen(fqdn, 256)); fqdn_type_ie *fqdn_ie_ptr = IE_TYPE_PTR_FROM_GTPV2C_IE(fqdn_type_ie, ie); strncpy((char *)fqdn_ie_ptr->fqdn, fqdn, strnlen(fqdn, 255) + 1); } #ifdef CP_BUILD pfcp_config_t config; int decode_check_csr(gtpv2c_header_t *gtpv2c_rx, create_sess_req_t *csr, uint8_t *cp_type) { int ret = 0; ret = decode_create_sess_req((uint8_t *) gtpv2c_rx, csr); if (!ret){ clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Decoding for csr req failed", LOG_VALUE); return -1; } if (csr->indctn_flgs.header.len && csr->indctn_flgs.indication_uimsi) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Unauthenticated IMSI Not Yet Implemented - " "Dropping packet\n", LOG_VALUE); return GTPV2C_CAUSE_IMSI_NOT_KNOWN; } /* Dynamically Set the gateway modes */ if (csr->pgw_s5s8_addr_ctl_plane_or_pmip.header.len != 0) { if((config.s5s8_ip_type != PDN_IP_TYPE_IPV4V6) && ((csr->pgw_s5s8_addr_ctl_plane_or_pmip.v4 && csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv4_address != 0 && config.s5s8_ip_type != PDN_IP_TYPE_IPV4) || (csr->pgw_s5s8_addr_ctl_plane_or_pmip.v6 && *csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv6_address != 0 && config.s5s8_ip_type != PDN_IP_TYPE_IPV6))){ clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"SGW S5S8 interface not supported for" " Requested PGW IP type\n", LOG_VALUE); return GTPV2C_CAUSE_REQUEST_REJECTED; } struct in6_addr temp = {0}; if ((csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv4_address != 0 || memcmp(csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv6_address, temp.s6_addr, IPV6_ADDRESS_LEN)) && (config.s5s8_ip.s_addr != 0 || *config.s5s8_ip_v6.s6_addr)) { /* Selection Criteria for Combined GW, SAEGWC */ if((((csr->pgw_s5s8_addr_ctl_plane_or_pmip.v4) && (csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv4_address == config.s5s8_ip.s_addr)) || (csr->pgw_s5s8_addr_ctl_plane_or_pmip.v6 && (!memcmp(csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv6_address, temp.s6_addr, IPV6_ADDRESS_LEN) || (memcmp(csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv6_address, config.s5s8_ip_v6.s6_addr, IPV6_ADDRESS_LEN) == 0)))) || (((csr->pgw_s5s8_addr_ctl_plane_or_pmip.v4) && (csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv4_address == config.s11_ip.s_addr)) || (csr->pgw_s5s8_addr_ctl_plane_or_pmip.v6 && memcmp(csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv6_address, config.s11_ip_v6.s6_addr, IPV6_ADDRESS_LEN) == 0))) { /* Condition to Allow GW run as a Combined GW */ if (config.cp_type == SAEGWC) { *cp_type = SAEGWC; } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Not Valid CSR Request for configured GW, Gateway Mode:%s\n", LOG_VALUE, config.cp_type == SGWC ? "SGW-C" : config.cp_type == PGWC ? "PGW-C" : config.cp_type == SAEGWC ? "SAEGW-C" : "UNKNOWN"); return GTPV2C_CAUSE_REQUEST_REJECTED; } } else { /* Selection Criteria for SGWC */ if ((config.cp_type != PGWC) && ((csr->pgw_s5s8_addr_ctl_plane_or_pmip.v4 && (csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv4_address != csr->sender_fteid_ctl_plane.ipv4_address)) || (csr->pgw_s5s8_addr_ctl_plane_or_pmip.v6 && memcmp(csr->pgw_s5s8_addr_ctl_plane_or_pmip.ipv6_address, csr->sender_fteid_ctl_plane.ipv6_address, IPV6_ADDRESS_LEN) != 0))) { *cp_type = SGWC; } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Not Valid CSR Request for configured GW, Gateway Mode:%s\n", LOG_VALUE, config.cp_type == SGWC ? "SGW-C" : config.cp_type == PGWC ? "PGW-C" : config.cp_type == SAEGWC ? "SAEGW-C" : "UNKNOWN"); return GTPV2C_CAUSE_REQUEST_REJECTED; } } } else { /* Condition to Allow GW run as a Combined GW */ if (config.cp_type == SAEGWC) { *cp_type = SAEGWC; } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Not Valid CSR Request for configured GW, Gateway Mode:%s\n", LOG_VALUE, config.cp_type == SGWC ? "SGW-C" : config.cp_type == PGWC ? "PGW-C" : config.cp_type == SAEGWC ? "SAEGW-C" : "UNKNOWN"); return GTPV2C_CAUSE_REQUEST_REJECTED; } } } else if (csr->sender_fteid_ctl_plane.interface_type == S5_S8_SGW_GTP_C) { /* Selection Criteria for PGWC */ if (config.cp_type != SGWC) { *cp_type = PGWC; } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Not Valid CSR Request for configured GW, Gateway Mode:%s\n", LOG_VALUE, config.cp_type == SGWC ? "SGW-C" : config.cp_type == PGWC ? "PGW-C" : config.cp_type == SAEGWC ? "SAEGW-C" : "UNKNOWN"); return GTPV2C_CAUSE_REQUEST_REJECTED; } } else { if (config.cp_type == SAEGWC) { *cp_type = SAEGWC; } else { /* Not meet upto selection Criteria */ clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Failed to Select or Set Gateway Mode, Dropping packet\n", LOG_VALUE); return GTPV2C_CAUSE_REQUEST_REJECTED; } } if ((*cp_type == SGWC) && (!csr->pgw_s5s8_addr_ctl_plane_or_pmip.header.len)) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Mandatory IE missing. Dropping packet len:%u\n", LOG_VALUE, csr->pgw_s5s8_addr_ctl_plane_or_pmip.header.len); return GTPV2C_CAUSE_MANDATORY_IE_MISSING; } if (!csr->sender_fteid_ctl_plane.header.len || !csr->imsi.header.len || !csr->apn_ambr.header.len || !csr->pdn_type.header.len || !csr->rat_type.header.len || !csr->apn.header.len) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Mandatory IE missing. Dropping packet\n", LOG_VALUE); return GTPV2C_CAUSE_MANDATORY_IE_MISSING; } for (uint8_t iCnt = 0; iCnt < csr->bearer_count; ++iCnt) { if (!csr->bearer_contexts_to_be_created[iCnt].header.len || !csr->bearer_contexts_to_be_created[iCnt].bearer_lvl_qos.header.len) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Bearer Context IE missing. Dropping packet\n", LOG_VALUE); return GTPV2C_CAUSE_MANDATORY_IE_MISSING; } } return 0; } void set_serving_network(gtp_serving_network_ie_t *serving_nw, create_sess_req_t *csr, enum ie_instance instance) { set_ie_header(&serving_nw->header, GTP_IE_SERVING_NETWORK, instance, sizeof(uint8_t)*3); serving_nw->mcc_digit_2 = csr->serving_network.mcc_digit_2; serving_nw->mcc_digit_1 = csr->serving_network.mcc_digit_1; serving_nw->mnc_digit_3 = csr->serving_network.mnc_digit_3; serving_nw->mcc_digit_3 = csr->serving_network.mcc_digit_3; serving_nw->mnc_digit_2 = csr->serving_network.mnc_digit_2; serving_nw->mnc_digit_1 = csr->serving_network.mnc_digit_1; } void set_ue_timezone(gtp_ue_time_zone_ie_t *ue_timezone, create_sess_req_t *csr, enum ie_instance instance) { set_ie_header(&ue_timezone->header, GTP_IE_UE_TIME_ZONE, instance, sizeof(uint8_t)*2); ue_timezone->time_zone = csr->ue_time_zone.time_zone; ue_timezone->spare2 = csr->ue_time_zone.spare2; ue_timezone->daylt_svng_time = csr->ue_time_zone.daylt_svng_time; } void set_mapped_ue_usage_type(gtp_mapped_ue_usage_type_ie_t *ie, uint16_t usage_type_value) { set_ie_header(&ie->header, GTP_IE_MAPPED_UE_USAGE_TYPE, 0, sizeof(uint16_t)); ie->mapped_ue_usage_type = usage_type_value; } void set_presence_reporting_area_action_ie(gtp_pres_rptng_area_act_ie_t *ie, ue_context *context){ uint8_t size = 0; ie->action = context->pre_rptng_area_act->action; size += sizeof(uint8_t); ie->pres_rptng_area_idnt = context->pre_rptng_area_act->pres_rptng_area_idnt; size += 3*sizeof(uint8_t); ie->number_of_tai = context->pre_rptng_area_act->number_of_tai; ie->number_of_rai = context->pre_rptng_area_act->number_of_rai; size += sizeof(uint8_t); ie->nbr_of_macro_enb = context->pre_rptng_area_act->nbr_of_macro_enb; size += sizeof(uint8_t); ie->nbr_of_home_enb = context->pre_rptng_area_act->nbr_of_home_enb; size += sizeof(uint8_t); ie->number_of_ecgi = context->pre_rptng_area_act->number_of_ecgi; size += sizeof(uint8_t); ie->number_of_sai = context->pre_rptng_area_act->number_of_sai; size += sizeof(uint8_t); ie->number_of_cgi = context->pre_rptng_area_act->number_of_cgi; size += sizeof(uint8_t); ie->nbr_of_extnded_macro_enb = context->pre_rptng_area_act->nbr_of_extnded_macro_enb; size += sizeof(uint8_t); uint32_t cpy_size = 0; if(ie->number_of_tai){ cpy_size = ie->number_of_tai * sizeof(tai_field_t); memcpy(&ie->tais, &context->pre_rptng_area_act->tais, cpy_size); size += sizeof(tai_field_t); } if(ie->number_of_rai){ cpy_size = ie->number_of_rai * sizeof(rai_field_t); memcpy(&ie->rais, &context->pre_rptng_area_act->rais, cpy_size); size += sizeof(rai_field_t); } if(ie->nbr_of_macro_enb){ cpy_size = ie->nbr_of_macro_enb * sizeof(macro_enb_id_fld_t); memcpy(&ie->macro_enb_ids, &context->pre_rptng_area_act->macro_enodeb_ids, cpy_size); size += sizeof(macro_enb_id_fld_t); } if(ie->nbr_of_home_enb){ cpy_size = ie->nbr_of_home_enb * sizeof(home_enb_id_fld_t); memcpy(&ie->home_enb_ids, &context->pre_rptng_area_act->home_enb_ids, cpy_size); size += sizeof(home_enb_id_fld_t); } if(ie->number_of_ecgi){ cpy_size = ie->number_of_ecgi * sizeof(ecgi_field_t); memcpy(&ie->ecgis, &context->pre_rptng_area_act->ecgis, cpy_size); size += sizeof(ecgi_field_t); } if(ie->number_of_sai){ cpy_size = ie->number_of_sai * sizeof(sai_field_t); memcpy(&ie->sais, &context->pre_rptng_area_act->sais, cpy_size); size += sizeof(sai_field_t); } if(ie->number_of_cgi){ cpy_size = ie->number_of_cgi * sizeof(cgi_field_t); memcpy(&ie->cgis, &context->pre_rptng_area_act->cgis, cpy_size); size += sizeof(cgi_field_t); } if(ie->nbr_of_extnded_macro_enb){ cpy_size = ie->nbr_of_extnded_macro_enb * sizeof(extnded_macro_enb_id_fld_t); memcpy(&ie->extnded_macro_enb_ids, &context->pre_rptng_area_act->extended_macro_enodeb_ids, cpy_size); size += sizeof(extnded_macro_enb_id_fld_t); } set_ie_header(&ie->header, GTP_IE_PRES_RPTNG_AREA_ACT, 0, size); return; } void set_presence_reporting_area_info_ie(gtp_pres_rptng_area_info_ie_t *ie, ue_context *context){ int size = 0; ie->pra_identifier = context->pre_rptng_area_info.pra_identifier; size += 3*sizeof(uint8_t); ie->inapra = context->pre_rptng_area_info.inapra; ie->opra = context->pre_rptng_area_info.opra; ie->ipra = context->pre_rptng_area_info.ipra; size += sizeof(uint8_t); set_ie_header(&ie->header, GTP_IE_PRES_RPTNG_AREA_INFO, 0, size); return; } #endif /* CP_BUILD */
nikhilc149/e-utran-features-bug-fixes
cp/cp_init.c
<gh_stars>0 /* * Copyright (c) 2019 Sprint * Copyright (c) 2020 T-Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <signal.h> #include <rte_ip.h> #include <rte_udp.h> #include <rte_hash_crc.h> #include <errno.h> #include <sys/time.h> #include "ue.h" #include "pfcp.h" #include "gtpv2c.h" #include "cp_stats.h" #include "pfcp_set_ie.h" #include "pfcp_session.h" #include "pfcp_association.h" #include "ngic_timer.h" #include "sm_struct.h" #include "cp_timer.h" #include "cp_config.h" #include "redis_client.h" #include "pfcp_util.h" #include "cdnshelper.h" #include "interface.h" #include "predef_rule_init.h" int s11_fd = -1; int s11_fd_v6 = -1; void *ddf2_fd = NULL; int s5s8_fd = -1; int s5s8_fd_v6 = -1; int pfcp_fd = -1; int pfcp_fd_v6 = -1; int s11_pcap_fd = -1; pcap_t *pcap_reader; pcap_dumper_t *pcap_dumper; struct cp_stats_t cp_stats; extern pfcp_config_t config; extern udp_sock_t my_sock; // struct sockaddr_in s11_sockaddr; // struct sockaddr_in6 s11_sockaddr_ipv6; peer_addr_t s11_sockaddr; // struct sockaddr_in6 s5s8_sockaddr_ipv6; // struct sockaddr_in s5s8_sockaddr; peer_addr_t s5s8_sockaddr; extern int clSystemLog; /* MME */ peer_addr_t s11_mme_sockaddr; /* S5S8 */ peer_addr_t s5s8_recv_sockaddr; /* PFCP */ in_port_t pfcp_port; peer_addr_t pfcp_sockaddr; /* UPF PFCP */ in_port_t upf_pfcp_port; peer_addr_t upf_pfcp_sockaddr; socklen_t s5s8_sockaddr_len = sizeof(s5s8_sockaddr.ipv4); socklen_t s5s8_sockaddr_ipv6_len = sizeof(s5s8_sockaddr.ipv6); socklen_t s11_mme_sockaddr_len = sizeof(s11_mme_sockaddr.ipv4); socklen_t s11_mme_sockaddr_ipv6_len = sizeof(s11_mme_sockaddr.ipv6); in_port_t s11_port; in_port_t s5s8_port; uint8_t s11_rx_buf[MAX_GTPV2C_UDP_LEN]; uint8_t s11_tx_buf[MAX_GTPV2C_UDP_LEN]; uint8_t pfcp_tx_buf[MAX_GTPV2C_UDP_LEN]; uint8_t msg_buf_t[MAX_GTPV2C_UDP_LEN]; uint8_t tx_buf[MAX_GTPV2C_UDP_LEN] = {0}; #ifdef USE_REST /* ECHO PKTS HANDLING */ uint8_t echo_tx_buf[MAX_GTPV2C_UDP_LEN]; #endif /* USE_REST */ uint8_t s5s8_rx_buf[MAX_GTPV2C_UDP_LEN] = {0}; uint8_t s5s8_tx_buf[MAX_GTPV2C_UDP_LEN] = {0}; #ifdef SYNC_STATS /** * @brief : Initializes the hash table used to account for statstics of req and resp time. * @param : void * @return : void */ void init_stats_hash(void) { struct rte_hash_parameters rte_hash_params = { .name = "stats_hash", .entries = STATS_HASH_SIZE, .key_len = sizeof(uint64_t), .hash_func = rte_hash_crc, .hash_func_init_val = 0, .socket_id = rte_socket_id(), }; stats_hash = rte_hash_create(&rte_hash_params); if (!stats_hash) { rte_panic("%s hash create failed: %s (%u)\n", rte_hash_params.name, rte_strerror(rte_errno), rte_errno); } } #endif /* SYNC_STATS */ void stats_update(uint8_t msg_type) { switch (config.cp_type) { case SGWC: case SAEGWC: switch (msg_type) { case GTP_CREATE_SESSION_REQ: cp_stats.create_session++; break; case GTP_DELETE_SESSION_REQ: cp_stats.delete_session++; break; case GTP_MODIFY_BEARER_REQ: cp_stats.modify_bearer++; break; case GTP_RELEASE_ACCESS_BEARERS_REQ: cp_stats.rel_access_bearer++; break; case GTP_BEARER_RESOURCE_CMD: cp_stats.bearer_resource++; break; case GTP_DELETE_BEARER_RSP: cp_stats.delete_bearer++; return; case GTP_DOWNLINK_DATA_NOTIFICATION_ACK: cp_stats.ddn_ack++; break; case GTP_ECHO_REQ: cp_stats.echo++; break; } break; case PGWC: switch (msg_type) { case GTP_CREATE_SESSION_REQ: cp_stats.create_session++; break; case GTP_DELETE_SESSION_REQ: cp_stats.delete_session++; break; } break; default: rte_panic("main.c::control_plane::cp_stats-" "Unknown gw_cfg= %d.", config.cp_type); break; } } void dump_pcap(uint16_t payload_length, uint8_t *tx_buf) { static struct pcap_pkthdr pcap_tx_header; gettimeofday(&pcap_tx_header.ts, NULL); pcap_tx_header.caplen = payload_length + sizeof(struct ether_hdr) + sizeof(struct ipv4_hdr) + sizeof(struct udp_hdr); pcap_tx_header.len = payload_length + sizeof(struct ether_hdr) + sizeof(struct ipv4_hdr) + sizeof(struct udp_hdr); uint8_t dump_buf[MAX_GTPV2C_UDP_LEN + sizeof(struct ether_hdr) + sizeof(struct ipv4_hdr) + sizeof(struct udp_hdr)]; struct ether_hdr *eh = (struct ether_hdr *) dump_buf; memset(&eh->d_addr, '\0', sizeof(struct ether_addr)); memset(&eh->s_addr, '\0', sizeof(struct ether_addr)); eh->ether_type = htons(ETHER_TYPE_IPv4); struct ipv4_hdr *ih = (struct ipv4_hdr *) &eh[1]; /* s11 mme ip not exist in cp config */ //ih->dst_addr = config.s11_mme_ip.s_addr; ih->src_addr = config.s11_ip.s_addr; ih->next_proto_id = IPPROTO_UDP; ih->version_ihl = PCAP_VIHL; ih->total_length = ntohs(payload_length + sizeof(struct udp_hdr) + sizeof(struct ipv4_hdr)); ih->time_to_live = PCAP_TTL; struct udp_hdr *uh = (struct udp_hdr *) &ih[1]; uh->dgram_len = htons( ntohs(ih->total_length) - sizeof(struct ipv4_hdr)); uh->dst_port = htons(GTPC_UDP_PORT); uh->src_port = htons(GTPC_UDP_PORT); void *payload = &uh[1]; memcpy(payload, tx_buf, payload_length); pcap_dump((u_char *) pcap_dumper, &pcap_tx_header, dump_buf); fflush(pcap_dump_file(pcap_dumper)); } /** * @brief : Util to send or dump gtpv2c messages * @param : fd, interface indentifier * @param : t_tx, buffer to store data for peer node * @param : context, UE context for lawful interception * @return : void */ void timer_retry_send(int fd_v4, int fd_v6, peerData *t_tx, ue_context *context) { int bytes_tx; peer_addr_t tx_sockaddr; tx_sockaddr.type = t_tx->dstIP.ip_type; if (t_tx->dstIP.ip_type == PDN_TYPE_IPV4) { tx_sockaddr.ipv4.sin_family = AF_INET; tx_sockaddr.ipv4.sin_port = t_tx->dstPort; tx_sockaddr.ipv4.sin_addr.s_addr = t_tx->dstIP.ipv4_addr; } else { tx_sockaddr.ipv6.sin6_family = AF_INET6; tx_sockaddr.ipv6.sin6_port = t_tx->dstPort; memcpy(&tx_sockaddr.ipv6.sin6_addr.s6_addr, t_tx->dstIP.ipv6_addr, IPV6_ADDRESS_LEN); } if (pcap_dumper) { dump_pcap(t_tx->buf_len, t_tx->buf); } else { bytes_tx = gtpv2c_send(fd_v4, fd_v6, t_tx->buf, t_tx->buf_len, tx_sockaddr, SENT); clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"NGIC- main.c::" "gtpv2c_send()""\n\tgtpv2c_if_fd_v4= %d::gtpv2c_if_fd_v6= %d\n", LOG_VALUE, fd_v4, fd_v6); if (NULL != context) { uint8_t tx_buf[MAX_GTPV2C_UDP_LEN]; uint16_t payload_length; payload_length = t_tx->buf_len; memset(tx_buf, 0, MAX_GTPV2C_UDP_LEN); memcpy(tx_buf, t_tx->buf, payload_length); switch(t_tx->portId) { case GX_IFACE: break; case S11_IFACE: /* copy packet for user level packet copying or li */ if (context->dupl) { process_pkt_for_li( context, S11_INTFC_OUT, tx_buf, payload_length, fill_ip_info(tx_sockaddr.type, config.s11_ip.s_addr, config.s11_ip_v6.s6_addr), fill_ip_info(tx_sockaddr.type, tx_sockaddr.ipv4.sin_addr.s_addr, tx_sockaddr.ipv6.sin6_addr.s6_addr), config.s11_port, ((tx_sockaddr.type == IPTYPE_IPV4_LI) ? tx_sockaddr.ipv4.sin_port : tx_sockaddr.ipv6.sin6_port)); } break; case S5S8_IFACE: /* copy packet for user level packet copying or li */ if (context->dupl) { process_pkt_for_li( context, S5S8_C_INTFC_OUT, tx_buf, payload_length, fill_ip_info(tx_sockaddr.type, config.s5s8_ip.s_addr, config.s5s8_ip_v6.s6_addr), fill_ip_info(tx_sockaddr.type, tx_sockaddr.ipv4.sin_addr.s_addr, tx_sockaddr.ipv6.sin6_addr.s6_addr), config.s5s8_port, ((tx_sockaddr.type == IPTYPE_IPV4_LI) ? tx_sockaddr.ipv4.sin_port : tx_sockaddr.ipv6.sin6_port)); } break; case PFCP_IFACE: /* copy packet for user level packet copying or li */ if (context->dupl) { process_pkt_for_li( context, SX_INTFC_OUT, tx_buf, payload_length, fill_ip_info(tx_sockaddr.type, config.pfcp_ip.s_addr, config.pfcp_ip_v6.s6_addr), fill_ip_info(tx_sockaddr.type, tx_sockaddr.ipv4.sin_addr.s_addr, tx_sockaddr.ipv6.sin6_addr.s6_addr), config.pfcp_port, ((tx_sockaddr.type == IPTYPE_IPV4_LI) ? tx_sockaddr.ipv4.sin_port : tx_sockaddr.ipv6.sin6_port)); } break; default: break; } } if (bytes_tx != (int) t_tx->buf_len) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Transmitted Incomplete Timer Retry Message:" "%u of %d tx bytes : %s\n", LOG_VALUE, t_tx->buf_len, bytes_tx, strerror(errno)); } } } int create_udp_socket_v4(uint32_t ipv4_addr, uint16_t port, peer_addr_t *addr) { int mode = 1; int fd = socket(AF_INET, SOCK_DGRAM, 0); socklen_t v4_addr_len = sizeof(addr->ipv4); if (fd < 0) { rte_panic("Socket call error : %s", strerror(errno)); return -1; } /*Below Option allows to bind to same port for multiple IPv6 addresses*/ setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &mode, sizeof(mode)); bzero(addr->ipv4.sin_zero, sizeof(addr->ipv4.sin_zero)); addr->ipv4.sin_family = AF_INET; addr->ipv4.sin_port = port; addr->ipv4.sin_addr.s_addr = ipv4_addr; int ret = bind(fd, (struct sockaddr *) &addr->ipv4, v4_addr_len); if (ret < 0) { rte_panic("Bind error for V4 UDP Socket %s:%u - %s\n", inet_ntoa(addr->ipv4.sin_addr), ntohs(addr->ipv4.sin_port), strerror(errno)); return -1; } addr->type = PDN_TYPE_IPV4; return fd; } int create_udp_socket_v6(uint8_t ipv6_addr[], uint16_t port, peer_addr_t *addr) { int mode = 1, ret = 0; socklen_t v6_addr_len = sizeof(addr->ipv6); int fd = socket(AF_INET6, SOCK_DGRAM, 0); if (fd < 0) { rte_panic("Socket call error : %s", strerror(errno)); return -1; } /*Below Option allows to bind to same port for multiple IPv6 addresses*/ setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &mode, sizeof(mode)); /*Below Option allows to bind to same port for IPv4 and IPv6 addresses*/ setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&mode, sizeof(mode)); addr->ipv6.sin6_family = AF_INET6; memcpy(addr->ipv6.sin6_addr.s6_addr, ipv6_addr, IPV6_ADDRESS_LEN); addr->ipv6.sin6_port = port; ret = bind(fd, (struct sockaddr *) &addr->ipv6, v6_addr_len); if (ret < 0) { rte_panic("Bind error for V6 UDP Socket "IPv6_FMT":%u - %s\n", IPv6_PRINT(addr->ipv6.sin6_addr), ntohs(addr->ipv4.sin_port), strerror(errno)); return -1; } addr->type = PDN_TYPE_IPV6; return fd; } int gtpv2c_send(int gtpv2c_if_fd_v4, int gtpv2c_if_fd_v6, uint8_t *gtpv2c_tx_buf, uint16_t gtpv2c_pyld_len, peer_addr_t dest_addr,Dir dir) { CLIinterface it; gtpv2c_header_t *gtpv2c_tx = (gtpv2c_header_t *) gtpv2c_tx_buf; gtpv2c_header_t *piggy_backed; int bytes_tx = 0; if (pcap_dumper) { dump_pcap(gtpv2c_pyld_len, gtpv2c_tx_buf); } else { if(dest_addr.type == PDN_TYPE_IPV4) { if(gtpv2c_if_fd_v4 <= 0) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"GTPV2C send not possible due to incompatiable " "IP Type at Source and Destination \n", LOG_VALUE); return 0; } bytes_tx = sendto(gtpv2c_if_fd_v4, gtpv2c_tx_buf, gtpv2c_pyld_len, MSG_DONTWAIT, (struct sockaddr *) &dest_addr.ipv4, sizeof(dest_addr.ipv4)); clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"NGIC- main.c::gtpv2c_send()" "on IPv4 socket " "\n\tgtpv2c_if_fd_v4 = %d, payload_length= %d ,Direction= %d," "tx bytes= %d\n", LOG_VALUE, gtpv2c_if_fd_v4, gtpv2c_pyld_len, dir, bytes_tx); } else if(dest_addr.type == PDN_TYPE_IPV6) { if(gtpv2c_if_fd_v6 <= 0) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"GTPV2C send not possible due to incompatiable " "IP Type at Source and Destination \n", LOG_VALUE); return 0; } bytes_tx = sendto(gtpv2c_if_fd_v6, gtpv2c_tx_buf, gtpv2c_pyld_len, MSG_DONTWAIT, (struct sockaddr *) &dest_addr.ipv6, sizeof(dest_addr.ipv6)); clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"NGIC- main.c::gtpv2c_send()" "on IPv6 socket " "\n\tgtpv2c_if_fd_v6 = %d, payload_length= %d ,Direction= %d," "tx bytes= %d\n", LOG_VALUE, gtpv2c_if_fd_v6, gtpv2c_pyld_len, dir, bytes_tx); } else { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Niether IPV4 nor IPV6 type is set " "of %d TYPE \n", LOG_VALUE, dest_addr.type); } } if (bytes_tx != (int) gtpv2c_pyld_len) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Transmitted Incomplete GTPv2c Message:" "%u of %d tx bytes\n", LOG_VALUE, gtpv2c_pyld_len, bytes_tx); } if(((gtpv2c_if_fd_v4 == s11_fd) && (gtpv2c_if_fd_v4 != -1)) || ((gtpv2c_if_fd_v6 == s11_fd_v6) && (gtpv2c_if_fd_v6 != -1))) { it = S11; } else if(((gtpv2c_if_fd_v4 == s5s8_fd) && (gtpv2c_if_fd_v4 != -1)) || ((gtpv2c_if_fd_v6 == s5s8_fd_v6) && (gtpv2c_if_fd_v6 != -1))) { if(cli_node.s5s8_selection == NOT_PRESENT) { cli_node.s5s8_selection = OSS_S5S8_SENDER; } it = S5S8; } else if (((gtpv2c_if_fd_v4 == pfcp_fd) && (gtpv2c_if_fd_v4 != -1)) || ((gtpv2c_if_fd_v6 == pfcp_fd_v6) && (gtpv2c_if_fd_v6 != -1))) { it = SX; } else { clLog(clSystemLog, eCLSeverityCritical,LOG_FORMAT"\nunknown file discriptor, " "IPV4 file discriptor = %d::IPV6 file discriptor = %d\n", LOG_VALUE, gtpv2c_if_fd_v4, gtpv2c_if_fd_v6); } update_cli_stats((peer_address_t *) &dest_addr, gtpv2c_tx->gtpc.message_type, dir, it); if(gtpv2c_tx->gtpc.piggyback) { piggy_backed = (gtpv2c_header_t*) ((uint8_t *)gtpv2c_tx + sizeof(gtpv2c_tx->gtpc) + ntohs(gtpv2c_tx->gtpc.message_len)); update_cli_stats((peer_address_t *) &dest_addr, piggy_backed->gtpc.message_type, dir, it); } return bytes_tx; } /** * @brief : Set dns configurations parameters * @param : void * @return : void */ static void set_dns_config(void) { if (config.use_dns){ set_dnscache_refresh_params(config.dns_cache.concurrent, config.dns_cache.percent, config.dns_cache.sec); set_dns_retry_params(config.dns_cache.timeoutms, config.dns_cache.tries); /* set OPS dns config */ for (uint32_t i = 0; i < config.ops_dns.nameserver_cnt; i++) { set_nameserver_config(config.ops_dns.nameserver_ip[i], DNS_PORT, DNS_PORT, NS_OPS); } set_dns_local_ip(NS_OPS, config.cp_dns_ip_buff); apply_nameserver_config(NS_OPS); init_save_dns_queries(NS_OPS, config.ops_dns.filename, config.ops_dns.freq_sec); load_dns_queries(NS_OPS, config.ops_dns.filename); /* set APP dns config */ for (uint32_t i = 0; i < config.app_dns.nameserver_cnt; i++) set_nameserver_config(config.app_dns.nameserver_ip[i], DNS_PORT, DNS_PORT, NS_APP); set_dns_local_ip(NS_APP, config.cp_dns_ip_buff); apply_nameserver_config(NS_APP); init_save_dns_queries(NS_APP, config.app_dns.filename, config.app_dns.freq_sec); load_dns_queries(NS_APP, config.app_dns.filename); } } void init_pfcp(void) { int fd = 0; upf_pfcp_sockaddr.ipv4.sin_port = htons(config.upf_pfcp_port); upf_pfcp_sockaddr.ipv6.sin6_port = htons(config.upf_pfcp_port); pfcp_port = htons(config.pfcp_port); if (config.pfcp_ip_type == PDN_TYPE_IPV6 || config.pfcp_ip_type == PDN_TYPE_IPV4_IPV6) { fd = create_udp_socket_v6(config.pfcp_ip_v6.s6_addr, pfcp_port, &pfcp_sockaddr); if (fd > 0) { my_sock.sock_fd_v6 = fd; pfcp_fd_v6 = fd; } } if (config.pfcp_ip_type == PDN_TYPE_IPV4 || config.pfcp_ip_type == PDN_TYPE_IPV4_IPV6) { fd = create_udp_socket_v4(config.pfcp_ip.s_addr, pfcp_port, &pfcp_sockaddr); if (fd > 0) { my_sock.sock_fd = fd; pfcp_fd = fd; } } if (config.use_dns == 0) { /* Initialize peer UPF inteface for sendto(.., dest_addr), If DNS is Disable */ upf_pfcp_port = htons(config.upf_pfcp_port); bzero(upf_pfcp_sockaddr.ipv4.sin_zero, sizeof(upf_pfcp_sockaddr.ipv4.sin_zero)); if ((config.pfcp_ip_type == PDN_TYPE_IPV6 || config.pfcp_ip_type == PDN_TYPE_IPV4_IPV6) && (config.upf_pfcp_ip_type == PDN_TYPE_IPV6 || config.upf_pfcp_ip_type == PDN_TYPE_IPV4_IPV6)) { upf_pfcp_sockaddr.ipv6.sin6_family = AF_INET6; upf_pfcp_sockaddr.ipv6.sin6_port = upf_pfcp_port; memcpy(upf_pfcp_sockaddr.ipv6.sin6_addr.s6_addr, config.upf_pfcp_ip_v6.s6_addr, IPV6_ADDRESS_LEN); upf_pfcp_sockaddr.type = PDN_TYPE_IPV6; } else if ((config.pfcp_ip_type == PDN_TYPE_IPV4 || config.pfcp_ip_type == PDN_TYPE_IPV4_IPV6) && (config.upf_pfcp_ip_type == PDN_TYPE_IPV4 || config.upf_pfcp_ip_type == PDN_TYPE_IPV4_IPV6)) { upf_pfcp_sockaddr.ipv4.sin_family = AF_INET; upf_pfcp_sockaddr.ipv4.sin_port = upf_pfcp_port; upf_pfcp_sockaddr.ipv4.sin_addr.s_addr = config.upf_pfcp_ip.s_addr; upf_pfcp_sockaddr.type = PDN_TYPE_IPV4; } } clLog(clSystemLog, eCLSeverityInfo, LOG_FORMAT"NGIC- main.c::init_pfcp()" "\n\tpfcp_fd_v4 = %d :: \n\tpfcp_fd_v6 = %d :: " "\n\tpfcp_ip_v4 = %s :: \n\tpfcp_ip_v6 = "IPv6_FMT" ::" "\n\tpfcp_port = %d\n", LOG_VALUE, pfcp_fd, pfcp_fd_v6, inet_ntoa(config.pfcp_ip), IPv6_PRINT(config.pfcp_ip_v6), ntohs(pfcp_port)); } /** * @brief : Initalizes S11 interface if in use * @param : void * @return : void */ static void init_s11(void) { int fd = 0; /* TODO: Need to think*/ s11_mme_sockaddr.ipv4.sin_port = htons(config.s11_port); s11_mme_sockaddr.ipv6.sin6_port = htons(config.s11_port); s11_port = htons(config.s11_port); if (pcap_reader != NULL && pcap_dumper != NULL) return; if (config.s11_ip_type == PDN_TYPE_IPV6 || config.s11_ip_type == PDN_TYPE_IPV4_IPV6) { fd = create_udp_socket_v6(config.s11_ip_v6.s6_addr, s11_port, &s11_sockaddr); if (fd > 0) { my_sock.sock_fd_s11_v6 = fd; s11_fd_v6 = fd; } } if (config.s11_ip_type == PDN_TYPE_IPV4 || config.s11_ip_type == PDN_TYPE_IPV4_IPV6) { fd = create_udp_socket_v4(config.s11_ip.s_addr, s11_port, &s11_sockaddr); if (fd > 0) { my_sock.sock_fd_s11 = fd; s11_fd = fd; } } clLog(clSystemLog, eCLSeverityInfo, LOG_FORMAT"NGIC- main.c::init_s11()" "\n\ts11_fd_v4 = %d :: \n\ts11_fd_v6= %d :: " "\n\ts11_ip_v4 = %s :: \n\ts11_ip_v6 = "IPv6_FMT" ::" "\n\ts11_port = %d\n", LOG_VALUE, s11_fd, s11_fd_v6, inet_ntoa(config.s11_ip), IPv6_PRINT(config.s11_ip_v6), ntohs(s11_port)); } /** * @brief : Initalizes s5s8_sgwc interface if in use * @param : void * @return : void */ static void init_s5s8(void) { int fd = 0; /* TODO: Need to think*/ s5s8_recv_sockaddr.ipv4.sin_port = htons(config.s5s8_port); s5s8_recv_sockaddr.ipv6.sin6_port = htons(config.s5s8_port); s5s8_port = htons(config.s5s8_port); if (pcap_reader != NULL && pcap_dumper != NULL) return; if (config.s5s8_ip_type == PDN_TYPE_IPV6 || config.s5s8_ip_type == PDN_TYPE_IPV4_IPV6) { fd = create_udp_socket_v6(config.s5s8_ip_v6.s6_addr, s5s8_port, &s5s8_sockaddr); if (fd > 0) { my_sock.sock_fd_s5s8_v6 = fd; s5s8_fd_v6 = fd; } } if (config.s5s8_ip_type == PDN_TYPE_IPV4 || config.s5s8_ip_type == PDN_TYPE_IPV4_IPV6) { fd = create_udp_socket_v4(config.s5s8_ip.s_addr, s5s8_port, &s5s8_sockaddr); if (fd > 0) { my_sock.sock_fd_s5s8 = fd; s5s8_fd = fd; } } clLog(clSystemLog, eCLSeverityInfo, LOG_FORMAT"NGIC- main.c::init_s5s8_sgwc()" "\n\ts5s8_fd_v4 = %d :: \n\ts5s8_fd_v6 = %d :: " "\n\ts5s8_ip_v4 = %s :: \n\ts5s8_ip_v6 = "IPv6_FMT" ::" "\n\ts5s8_port = %d\n", LOG_VALUE, s5s8_fd, s5s8_fd_v6, inet_ntoa(config.s5s8_ip), IPv6_PRINT(config.s5s8_ip_v6), ntohs(s5s8_port)); } void initialize_tables_on_dp(void) { #ifdef CP_DP_TABLE_CONFIG struct dp_id dp_id = { .id = DPN_ID }; snprintf(dp_id.name, MAX_LEN, SDF_FILTER_TABLE); if (sdf_filter_table_create(dp_id, SDF_FILTER_TABLE_SIZE)) rte_panic("sdf_filter_table creation failed\n"); snprintf(dp_id.name, MAX_LEN, ADC_TABLE); if (adc_table_create(dp_id, ADC_TABLE_SIZE)) rte_panic("adc_table creation failed\n"); snprintf(dp_id.name, MAX_LEN, PCC_TABLE); if (pcc_table_create(dp_id, PCC_TABLE_SIZE)) rte_panic("pcc_table creation failed\n"); snprintf(dp_id.name, MAX_LEN, METER_PROFILE_SDF_TABLE); if (meter_profile_table_create(dp_id, METER_PROFILE_SDF_TABLE_SIZE)) rte_panic("meter_profile_sdf_table creation failed\n"); snprintf(dp_id.name,MAX_LEN, SESSION_TABLE); if (session_table_create(dp_id, LDB_ENTRIES_DEFAULT)) rte_panic("session_table creation failed\n"); #endif } void init_dp_rule_tables(void) { #ifdef CP_DP_TABLE_CONFIG initialize_tables_on_dp(); #endif clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"Reading predefined rules from files.\n", LOG_VALUE); init_packet_filters(); clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"Reading predefined adc rules\n", LOG_VALUE); parse_adc_rules(); clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"Reading predefined adc rules completed\n", LOG_VALUE); clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"Read predefined rules and successfully stored in internal tables.\n", LOG_VALUE); } /** * @brief : Initializes Control Plane data structures, packet filters, and calls for the * Data Plane to create required tables */ void init_cp(void) { init_pfcp(); switch (config.cp_type) { case SGWC: init_s11(); case PGWC: init_s5s8(); break; case SAEGWC: init_s11(); init_s5s8(); break; default: rte_panic("main.c::init_cp()-" "Unknown CP_TYPE= %u\n", config.cp_type); break; } create_ue_hash(); create_upf_context_hash(); create_gx_context_hash(); create_upf_by_ue_hash(); create_li_info_hash(); if(config.use_dns) set_dns_config(); } int init_redis(void) { redis_config_t cfg = {0}; cfg.type = REDIS_TLS; if (config.redis_server_ip_type != config.cp_redis_ip_type) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Invalid Redis configuration " "Use only ipv4 or only ipv6 for " "connection\n", LOG_VALUE); return -1; } strncpy(cfg.conf.tls.cert_path, config.redis_cert_path, PATH_MAX); strncat(cfg.conf.tls.cert_path,"/redis.crt", PATH_MAX); strncpy(cfg.conf.tls.key_path, config.redis_cert_path, PATH_MAX); strncat(cfg.conf.tls.key_path,"/redis.key", PATH_MAX); strncpy(cfg.conf.tls.ca_cert_path, config.redis_cert_path, PATH_MAX); strncat(cfg.conf.tls.ca_cert_path,"/ca.crt", PATH_MAX); /*Store redis ip and cp redis ip*/ cfg.conf.tls.port = (int)config.redis_port; snprintf(cfg.conf.tls.host, IP_BUFF_SIZE, "%s", config.redis_ip_buff); snprintf(cfg.cp_ip, IP_BUFF_SIZE, "%s", config.cp_redis_ip_buff); struct timeval tm = {REDIS_CONN_TIMEOUT, 0}; cfg.conf.tls.timeout = tm; ctx = redis_connect(&cfg); if(ctx == NULL) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Connection to redis server failed," "Unable to send CDR to redis server\n", LOG_VALUE); return -1; } else { clLog(clSystemLog, eCLSeverityInfo,LOG_FORMAT"Redis Server" "Connected Succesfully\n", LOG_VALUE); } return 0; }
nikhilc149/e-utran-features-bug-fixes
dp/up_acl.h
/* * Copyright (c) 2019 Sprint * Copyright (c) 2020 T-Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _UP_ACL_H_ #define _UP_ACL_H_ /** * @file * This file contains macros, data structure definitions and function * prototypes of Access Control List. */ #include <rte_acl.h> #include <rte_ip.h> #include <acl.h> #include "pfcp_up_struct.h" #include "vepc_cp_dp_api.h" #include "util.h" /** * Default SDF Rule ID to DROP (initialization) */ #define SDF_DEFAULT_DROP_RULE_ID (MAX_SDF_RULE_NUM - 1) #define IPV6_ADDR_U16 (IPV6_ADDRESS_LEN / sizeof(uint16_t)) #define IPV6_ADDR_U32 (IPV6_ADDRESS_LEN / sizeof(uint32_t)) enum { PROTO_FIELD_IPV4, SRC_FIELD_IPV4, DST_FIELD_IPV4, SRCP_FIELD_IPV4, DSTP_FIELD_IPV4, NUM_FIELDS_IPV4 }; enum { PROTO_FIELD_IPV6, SRC1_FIELD_IPV6, SRC2_FIELD_IPV6, SRC3_FIELD_IPV6, SRC4_FIELD_IPV6, DST1_FIELD_IPV6, DST2_FIELD_IPV6, DST3_FIELD_IPV6, DST4_FIELD_IPV6, NUM_FIELDS_IPV6 }; enum { RTE_ACL_IPV4VLAN_PROTO, RTE_ACL_IPV4VLAN_VLAN, RTE_ACL_IPV4VLAN_SRC, RTE_ACL_IPV4VLAN_DST, RTE_ACL_IPV4VLAN_PORTS, RTE_ACL_IPV4VLAN_NUM }; enum { CB_FLD_SRC_ADDR, CB_FLD_DST_ADDR, CB_FLD_SRC_PORT_LOW, CB_FLD_SRC_PORT_DLM, CB_FLD_SRC_PORT_HIGH, CB_FLD_DST_PORT_LOW, CB_FLD_DST_PORT_DLM, CB_FLD_DST_PORT_HIGH, CB_FLD_PROTO, CB_FLD_USERDATA, CB_FLD_NUM, }; enum { CB_IPV6_FLD_SRC_ADDR, CB_IPV6_FLD_DST_ADDR, CB_IPV6_FLD_PROTO, CB_IPV6_FLD_USERDATA, CB_IPV6_FLD_NUM, }; enum rule_ip_type { RULE_IPV6, RULE_IPV4 }; /** * @brief : Function for SDF lookup. * @param : m, pointer to pkts. * @param : nb_rx, num. of pkts. * @param : indx, acl table index * @return : Returns array containing search results for each input buf */ uint32_t * sdf_lookup(struct rte_mbuf **m, int nb_rx, uint32_t indx); /******************** UP SDF functions **********************/ /** * @brief : Get ACL Table index for SDF entry * @param : pkt_filter_entry, sdf packet filter entry structure * @param : is_ipv6, boolen for check the rule type for V6 IP of for V4 * @return : Returns 0 in case of success , -1 otherwise */ int get_acl_table_indx(struct sdf_pkt_filter *pkt_filter, uint8_t is_create); /** * @brief : Delete sdf filter rules in acl table. The entries are * first removed in local memory and then updated on ACL table. * @param : indx, ACL Table Index * @param : pkt_filter_entry, sdf packet filter entry structure * @return : Returns 0 in case of success , -1 otherwise */ int up_sdf_filter_entry_delete(uint32_t indx, struct sdf_pkt_filter *pkt_filter_entry); /** * @brief : Add default SDF entry * @param : indx, Acl table index * @param : precedence, PDR precedence * @param : direction, uplink or downlink * @return : Returns 0 in case of success , -1 otherwise */ int up_sdf_default_entry_add(uint32_t indx, uint32_t precedence, uint8_t direction); /** * @brief : Check Gate Status * @param : pdr, pdr information * @param : n, number of packets * @param : pkts_mask * @param : pkts_queue_mask * @param : direction, uplink or downlink * @return : Returns nothing */ void qer_gating(pdr_info_t **pdr, uint32_t n, uint64_t *pkts_mask, uint64_t *pkts_queue_mask, uint64_t *fd_pkts_mask, uint8_t direction); /** * @brief : swap the src and dst address for DL traffic. * @param : str, ip address in string format * @return : Returns nothing */ void swap_src_dst_ip(char *str); /** * @brief : Remove a single rule entry from ACL table . * @param : indx, ACL table index to identify the ACL table. * @param : pkt_filter_entry, rule which need to remove from the ACL table. * @return : Returns 0 in case of success , -1 otherwise */ int remove_rule_entry_acl(uint32_t indx, struct sdf_pkt_filter *pkt_filter_entry); /** * @brief : Delete the entire ACL table . * @param : indx, ACL table index to identify the ACL table. * @param : pkt_filter_entry, rule in the ACL table. * @return : Returns 0 in case of success , -1 otherwise */ int sdf_table_delete(uint32_t indx, struct sdf_pkt_filter *pkt_filter_entry); #endif /* _UP_ACL_H_ */
nikhilc149/e-utran-features-bug-fixes
dp/gtpu_echo.c
<reponame>nikhilc149/e-utran-features-bug-fixes /* * Copyright (c) 2019 Sprint * Copyright (c) 2020 T-Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <rte_log.h> #include <rte_common.h> #include <rte_ether.h> #include <rte_ip.h> #include <rte_udp.h> #include "gw_adapter.h" #include "ipv4.h" #include "ipv6.h" #include "gtpu.h" #include "util.h" extern uint8_t dp_restart_cntr; extern int clSystemLog; extern struct rte_mbuf *arp_pkt[NUM_SPGW_PORTS]; /* VS: */ //static uint8_t resp_cnt = 1; /** * @brief : Function to set echo request as echo response * @param : echo_pkt rte_mbuf pointer * @param : ip type * @return : Returns nothing */ static void reset_req_pkt_as_resp(struct rte_mbuf *echo_pkt, uint8_t ip_type) { /* Swap src and destination mac addresses */ struct ether_hdr *eth_h = rte_pktmbuf_mtod(echo_pkt, struct ether_hdr *); struct ether_addr tmp_mac; ether_addr_copy(&eth_h->d_addr, &tmp_mac); ether_addr_copy(&eth_h->s_addr, &eth_h->d_addr); ether_addr_copy(&tmp_mac, &eth_h->s_addr); uint16_t len = rte_pktmbuf_data_len(echo_pkt) - ETH_HDR_LEN; struct udp_hdr *udphdr = NULL; /* Swap src and dst IP addresses */ if (ip_type == IPV6_TYPE) { len = len - IPv6_HDR_SIZE; struct ipv6_hdr *ip_hdr = get_mtoip_v6(echo_pkt); uint8_t tmp_addr[16] = {0}; memcpy(tmp_addr, ip_hdr->dst_addr, IPV6_ADDR_LEN); memcpy(ip_hdr->dst_addr, ip_hdr->src_addr, IPV6_ADDR_LEN); memcpy(ip_hdr->src_addr, tmp_addr, IPV6_ADDR_LEN); ip_hdr->payload_len = htons(len); udphdr = get_mtoudp_v6(echo_pkt); } else { struct ipv4_hdr *ip_hdr = get_mtoip(echo_pkt); uint32_t tmp_ip = ip_hdr->dst_addr; ip_hdr->dst_addr = ip_hdr->src_addr; ip_hdr->src_addr = tmp_ip; ip_hdr->total_length = htons(len); udphdr = get_mtoudp(echo_pkt); len = len - IPV4_HDR_LEN; } /* Swap src and dst UDP ports */ uint16_t tmp_port = udphdr->dst_port; udphdr->dst_port = udphdr->src_port; udphdr->src_port = tmp_port; udphdr->dgram_len = htons(len); } /** * @brief : Function to set recovery IE * @param : echo_pkt rte_mbuf pointer * @param : ip type * @return : Returns 0 in case of success , -1 otherwise */ static int set_recovery(struct rte_mbuf *echo_pkt, uint8_t port_id, uint8_t ip_type) { uint16_t len = 0; struct gtpu_hdr *gtpu_hdr = get_mtogtpu(echo_pkt); gtpu_recovery_ie *recovery_ie = NULL; if (ip_type == IPV6_TYPE) { struct ipv6_hdr *ip_hdr = get_mtoip_v6(echo_pkt); gtpu_hdr = get_mtogtpu_v6(echo_pkt); len = ip_hdr->payload_len + IPv6_HDR_SIZE; } else { struct ipv4_hdr *ip_hdr = get_mtoip(echo_pkt); gtpu_hdr = get_mtogtpu(echo_pkt); len = ip_hdr->total_length; } /* VS: Fix the recovery IE issue for response */ /* Get the extra len bytes for recovery */ uint16_t extra_len = echo_pkt->pkt_len - (ETHER_HDR_LEN + ntohs(len)); if (extra_len < sizeof(gtpu_recovery_ie)) { recovery_ie = (gtpu_recovery_ie *)rte_pktmbuf_append(echo_pkt, (sizeof(gtpu_recovery_ie) - extra_len)); /* Checking the sufficient header room lenght for the recovery */ if ((echo_pkt->pkt_len - (ETHER_HDR_LEN + len)) < sizeof(gtpu_recovery_ie)) { fprintf(stderr, "ERROR: For recovery there is not sufficient lenght is allocated\n"); return -1; } } /* Point to the current location of the recovery ie */ recovery_ie = (gtpu_recovery_ie*)((char*)gtpu_hdr + GTPU_HDR_SIZE + ntohs(gtpu_hdr->msglen)); if (recovery_ie == NULL) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Couldn't " "append %lu bytes to memory buffer", LOG_VALUE, sizeof(gtpu_recovery_ie)); return -1; } gtpu_hdr->msgtype = GTPU_ECHO_RESPONSE; gtpu_hdr->msglen = htons(ntohs(gtpu_hdr->msglen)+ sizeof(gtpu_recovery_ie)); recovery_ie->type = GTPU_ECHO_RECOVERY; recovery_ie->restart_cntr = 0; clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"DP restart count: %d, recovery ie restart counter: %d \n", LOG_VALUE, dp_restart_cntr, recovery_ie->restart_cntr); return 0; } /** * @brief : Function to set checksum of IPv4 and UDP header * @param : echo_pkt rte_mbuf pointer * @param : ip type * @return : Returns nothing */ static void set_checksum(struct rte_mbuf *echo_pkt, uint8_t ip_type) { if (ip_type == IPV6_TYPE) { struct ipv6_hdr *ipv6hdr = get_mtoip_v6(echo_pkt); struct udp_hdr *udphdr = get_mtoudp_v6(echo_pkt); udphdr->dgram_cksum = 0; udphdr->dgram_cksum = rte_ipv6_udptcp_cksum(ipv6hdr, udphdr); } else { struct ipv4_hdr *ipv4hdr = get_mtoip(echo_pkt); ipv4hdr->hdr_checksum = 0; struct udp_hdr *udphdr = get_mtoudp(echo_pkt); udphdr->dgram_cksum = 0; udphdr->dgram_cksum = rte_ipv4_udptcp_cksum(ipv4hdr, udphdr); ipv4hdr->hdr_checksum = rte_ipv4_cksum(ipv4hdr); } } void process_echo_request(struct rte_mbuf *echo_pkt, uint8_t port_id, uint8_t ip_type) { int ret; ret = set_recovery(echo_pkt, port_id, ip_type); if (ret < 0) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Failed to create echo response\n", LOG_VALUE); return; } reset_req_pkt_as_resp(echo_pkt, ip_type); set_checksum(echo_pkt, ip_type); } /** * @brief : Function to set error indication header information * @param : gtpu_pkt rte_mbuf pointer * @param : ip type * @return : Returns 0 in case of success , -1 otherwise */ static int set_err_ind_hdr_info(struct rte_mbuf *gtpu_pkt, uint8_t port_id, uint8_t ip_type) { uint16_t len = 0, gtpu_len = 0; uint32_t teid = 0; struct gtpu_hdr *gtpu_hdr = NULL; gtpu_peer_address_ie *peer_addr_ie = NULL; struct teid_data_identifier *teid_1 = NULL; if (ip_type == IPV6_TYPE) { gtpu_hdr = (struct gtpu_hdr *)get_mtogtpu_v6(gtpu_pkt); } else { gtpu_hdr = (struct gtpu_hdr *)get_mtogtpu(gtpu_pkt); } /* Get the gtpu pkt len and teid */ gtpu_len = gtpu_hdr->msglen; teid = gtpu_hdr->teid; gtpu_hdr->teid = 0; gtpu_hdr->seq = 0; /* Reset the gtpu payload */ gtpu_hdr->msglen = 0; /* Update the gtpu pkt type*/ gtpu_hdr->msgtype = GTPU_ERROR_INDICATION; /* Update the pkt len*/ gtpu_hdr->msglen = htons(sizeof(struct teid_data_identifier)); teid_1 = (struct teid_data_identifier *)((char *)gtpu_hdr + GTPU_HDR_SIZE); if (teid_1 == NULL) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"ERR_IND:teid_1:Couldn't " "append %lu bytes to memory buffer", LOG_VALUE, sizeof(teid_1)); return -1; } /* Update the teid type */ teid_1->type = GTPU_TEID_DATA_TYPE; /* Update the teid */ teid_1->teid_data_identifier = teid; /* Point to the current location of the recovery ie */ peer_addr_ie = (gtpu_peer_address_ie *)((char*)gtpu_hdr + GTPU_HDR_SIZE + ntohs(gtpu_hdr->msglen)); if (peer_addr_ie == NULL) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"ERR_IND:peer_addr_ie:Couldn't " "append %lu bytes to memory buffer", LOG_VALUE, sizeof(peer_addr_ie)); return -1; } memset(peer_addr_ie, 0, sizeof(gtpu_peer_address_ie)); /* Fill the error indication info */ peer_addr_ie->type = GTPU_PEER_ADDRESS; len += (sizeof(peer_addr_ie->type) + sizeof(peer_addr_ie->length)); /* Fill the IP Address of the header */ if (ip_type == IPV6_TYPE) { struct ipv6_hdr *ip_hdr = get_mtoip_v6(gtpu_pkt); memcpy(peer_addr_ie->addr.ipv6_addr, ip_hdr->dst_addr, IPV6_ADDR_LEN); peer_addr_ie->length = htons(IPV6_ADDR_LEN); len += IPV6_ADDR_LEN; } else { struct ipv4_hdr *ip_hdr = get_mtoip(gtpu_pkt); peer_addr_ie->addr.ipv4_addr = ip_hdr->dst_addr; peer_addr_ie->length = htons(sizeof(peer_addr_ie->addr.ipv4_addr)); len += sizeof(peer_addr_ie->addr.ipv4_addr); } /* Update the gtpu payload length */ gtpu_hdr->msglen = htons(len + sizeof(struct teid_data_identifier)); gtpu_pkt->pkt_len = (gtpu_pkt->pkt_len - ntohs(gtpu_len)) + ntohs(gtpu_hdr->msglen); gtpu_pkt->data_len = gtpu_pkt->pkt_len; clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"Pkt descarded and sends error indication to peer node.\n", LOG_VALUE); return 0; } void send_error_indication_pkt(struct rte_mbuf *gtpu_pkt, uint8_t port_id) { int ret = 0; uint8_t ip_type = 0; /* Find the IP Type */ struct ether_hdr *ether = NULL; ether = (struct ether_hdr *)rte_pktmbuf_mtod(gtpu_pkt, uint8_t *); if (ether->ether_type == rte_cpu_to_be_16(ETHER_TYPE_IPv4)) { ip_type = IPV4_TYPE; } else if (ether->ether_type == rte_cpu_to_be_16(ETHER_TYPE_IPv6)) { ip_type = IPV6_TYPE; } else { clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"Failed to send error indication pkt, IP Address type not set \n", LOG_VALUE); return; } ret = set_err_ind_hdr_info(gtpu_pkt, port_id, ip_type); if (ret < 0) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Failed to update error indication pkt\n", LOG_VALUE); return; } reset_req_pkt_as_resp(gtpu_pkt, ip_type); set_checksum(gtpu_pkt, ip_type); /* Send the pkt to peer node */ /* Send ICMPv6 Router Advertisement resp */ int pkt_size = RTE_CACHE_LINE_ROUNDUP(sizeof(struct rte_mbuf)); /* arp_pkt @arp_xmpool[port_id] */ struct rte_mbuf *pkt1 = arp_pkt[port_id]; if (pkt1) { memcpy(pkt1, gtpu_pkt, pkt_size); if (rte_ring_enqueue(shared_ring[port_id], pkt1) == -ENOBUFS) { rte_pktmbuf_free(pkt1); clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"RA:Can't queue pkt- ring full" " Dropping pkt\n", LOG_VALUE); return; } clLog(clSystemLog, eCLSeverityDebug, LOG_FORMAT"ERROR_INDICATION: Sends the Error Indication pkts to peer node.\n",LOG_VALUE); } #ifdef STATS if(port_id == SGI_PORT_ID) { ++epc_app.dl_params[port_id].pkts_err_out; } else { ++epc_app.ul_params[port_id].pkts_err_out; } #endif /* STATS */ }
nikhilc149/e-utran-features-bug-fixes
cp/gtpv2c_messages/modify_access_bearer.c
<filename>cp/gtpv2c_messages/modify_access_bearer.c /* * Copyright (c) 2019 Sprint * Copyright (c) 2020 T-Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ue.h" #include "gtp_messages.h" #include "gtpv2c_set_ie.h" #include "../cp_dp_api/vepc_cp_dp_api.h" #include "../pfcp_messages/pfcp_set_ie.h" #include "cp/cp_app.h" #include "sm_enum.h" #include "gw_adapter.h" #include "pfcp_session.h" extern int clSystemLog; /** * @brief : from parameters, populates gtpv2c message 'modify access bearer response' and * populates required information elements as defined by * clause 7.2.8 3gpp 29.274 * @param : gtpv2c_tx * transmission buffer to contain 'modify access bearer request' message * @param : sequence * sequence number as described by clause 7.6 3gpp 29.274 * @param : context * UE Context data structure pertaining to the bearer to be modified * @param : bearer * bearer data structure to be modified * @return : Returns nothing */ void set_modify_access_bearer_response(gtpv2c_header_t *gtpv2c_tx, uint32_t sequence, ue_context *context, eps_bearer *bearer, mod_acc_bearers_req_t *mabr) { uint8_t _ebi = bearer->eps_bearer_id; int ebi_index = GET_EBI_INDEX(_ebi), ret = 0; if (ebi_index == -1) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Invalid EBI ID\n", LOG_VALUE); } upf_context_t *upf_ctx = NULL; /*Retrive bearer id from bearer --> context->pdns[]->upf_ip*/ if ((upf_context_entry_lookup(context->pdns[ebi_index]->upf_ip, &upf_ctx)) < 0) { return; } mod_acc_bearers_rsp_t mb_resp = {0}; set_gtpv2c_teid_header((gtpv2c_header_t *) &mb_resp, GTP_MODIFY_ACCESS_BEARER_RSP, context->s11_mme_gtpc_teid, sequence, 0); set_cause_accepted(&mb_resp.cause, IE_INSTANCE_ZERO); mb_resp.bearer_modify_count = mabr->bearer_modify_count; for (uint8_t uiCnt = 0; uiCnt < mabr->bearer_modify_count; ++uiCnt) { int ebi_index = GET_EBI_INDEX(mabr->bearer_contexts_to_be_modified[uiCnt].eps_bearer_id.ebi_ebi); if (ebi_index == -1) { clLog(clSystemLog, eCLSeverityCritical, LOG_FORMAT"Invalid EBI ID\n", LOG_VALUE); } bearer = context->eps_bearers[ebi_index]; set_ie_header(&mb_resp.bearer_contexts_modified[uiCnt].header, GTP_IE_BEARER_CONTEXT, IE_INSTANCE_ZERO, 0); set_cause_accepted(&mb_resp.bearer_contexts_modified[uiCnt].cause, IE_INSTANCE_ZERO); mb_resp.bearer_contexts_modified[uiCnt].header.len += sizeof(struct cause_ie_hdr_t) + IE_HEADER_SIZE; set_ebi(&mb_resp.bearer_contexts_modified[uiCnt].eps_bearer_id, IE_INSTANCE_ZERO, bearer->eps_bearer_id); mb_resp.bearer_contexts_modified[uiCnt].header.len += sizeof(uint8_t) + IE_HEADER_SIZE; if (context->cp_mode != PGWC) { if(context->indication_flag.s11tf == 1){ bearer->s11u_sgw_gtpu_teid = bearer->s1u_sgw_gtpu_teid; ret = set_address(&bearer->s11u_sgw_gtpu_ip, &bearer->s1u_sgw_gtpu_ip); if (ret < 0) { clLog(clSystemLog, eCLSeverityCritical,LOG_FORMAT "Error while assigning " "IP address", LOG_VALUE); } mb_resp.bearer_contexts_modified[uiCnt].header.len += set_gtpc_fteid(&mb_resp.bearer_contexts_modified[uiCnt].s11_u_sgw_fteid, GTPV2C_IFTYPE_S11U_SGW_GTPU, IE_INSTANCE_ZERO, upf_ctx->s1u_ip, bearer->s11u_sgw_gtpu_teid); }else{ mb_resp.bearer_contexts_modified[uiCnt].header.len += set_gtpc_fteid(&mb_resp.bearer_contexts_modified[uiCnt].s1u_sgw_fteid, GTPV2C_IFTYPE_S1U_SGW_GTPU, IE_INSTANCE_ZERO, upf_ctx->s1u_ip, bearer->s1u_sgw_gtpu_teid); } } } /* Update status of mbr processing for ue*/ context->req_status.seq = 0; context->req_status.status = REQ_PROCESS_DONE; encode_mod_acc_bearers_rsp(&mb_resp, (uint8_t *)gtpv2c_tx); }