0% found this document useful (0 votes)
39 views41 pages

Framework Mmi

The Android Asset Packaging Tool (AAPT) is a command-line utility that compiles, processes, and packages app resources into a format usable by the Android system. It performs key functions such as compiling resources, generating resource IDs, packaging APKs, and verifying APK structure. AAPT2, an improved version, offers faster processing and better error handling compared to its predecessor, while the document also discusses Runtime Resource Overlays (RRO) for dynamic resource modification and the Android architecture and boot-up sequence.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views41 pages

Framework Mmi

The Android Asset Packaging Tool (AAPT) is a command-line utility that compiles, processes, and packages app resources into a format usable by the Android system. It performs key functions such as compiling resources, generating resource IDs, packaging APKs, and verifying APK structure. AAPT2, an improved version, offers faster processing and better error handling compared to its predecessor, while the document also discusses Runtime Resource Overlays (RRO) for dynamic resource modification and the Android architecture and boot-up sequence.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 41

Android Asset Packaging Tool (AAPT)

1. What is AAPT?
The Android Asset Packaging Tool (AAPT) is a command-line utility used in the Android build
system to compile, process, and package app resources. It plays a crucial role in converting raw
assets and XML-based resources into a format that the Android system can understand and use at
runtime.
AAPT is part of the Android SDK (build-tools) and is automatically used by the Android
Gradle Plugin during the build process.

2. Key Functions of AAPT


AAPT is responsible for several critical tasks in Android app development:

a) Compiling Resources
• It compiles XML resource files (.xml), such as:

• Layout files (res/layout/*.xml)


• Drawable files (res/drawable/*.xml)
• Color files (res/values/colors.xml)
• String resources (res/values/strings.xml)
• Animation XML files (res/anim/*.xml)
• Nine-patch images (res/drawable/*.9.png)
• Converts these human-readable XML files into a binary format that Android can process
efficiently.

b) Generating the R.java file


• The R.java (or R.kt in Kotlin projects) file contains resource IDs for every resource in
the app.
c) Packaging Resources into an APK
• AAPT packages all compiled resources and assets into the APK file.
• Creates the resources.arsc file, which stores compiled resource data.

d) Verifying the APK Structure


• AAPT ensures that all required resources are present and formatted correctly.
• Checks for errors in AndroidManifest.xml, such as:
• Missing permissions
• Invalid activities or services
• Incorrectly defined resource references
e) Extracting APK Information
• AAPT can analyze an APK to retrieve metadata like:
• Package name
• App version
• Permissions requested
• Activities, services, and broadcast receivers

3. AAPT Commands and Usage


AAPT provides several useful commands to manipulate and inspect APK files.

a) Listing Contents of an APK

aapt list myapp.apk

• Displays a list of files inside the APK.

b) Dumping APK Information

aapt dump badging myapp.apk

• Extracts metadata from an APK, such as:


• Package name
• Version number
• Activities
• Permissions
• Intent filters

Example Output:

package: name='com.example.myapp' versionCode='10' versionName='1.0'


sdkVersion:'21'
targetSdkVersion:'30'
uses-permission: name='android.permission.INTERNET'
application-label:'MyApp'
launchable-activity: name='com.example.myapp.MainActivity'

c) Compiling Resources

aapt compile -o compiled_res.zip res/

• Compiles all resources into a .zip archive.

d) Packaging Resources into an APK

aapt package -f -m -J src -M AndroidManifest.xml -S res -I android.jar -F


myapp.apk
• Packages compiled resources and generates an APK file.

e) Extracting AndroidManifest.xml

aapt dump xmltree myapp.apk AndroidManifest.xml

• Extracts and parses the manifest file in a readable format.

f) Checking for Unused Resources


AAPT can also be used to detect and remove unused resources, which helps in reducing APK size.

4. AAPT vs AAPT2
Google introduced AAPT2 (AAPT version 2) to improve efficiency in the Android build process.

Feature AAPT AAPT2


Compilation Type Single-pass Two-pass (compiles first, links later)
Speed Slower Faster (parallel processing)
Error Handling Less informative Better error messages
APK Size Larger Smaller (better optimization)
Incremental Builds Not supported Supported

RRO (Runtime Resource Overlay)


RRO (Runtime Resource Overlay) is a mechanism used in Android to modify an app’s resources
dynamically at runtime without changing the APK. It allows modifying system and app resources
without modifying the source code.

Use Cases of RRO:


1. Theming and Customization:
• Modify system UI elements (e.g., dark mode, custom fonts, icon packs).
• Change resource values for different OEM devices.
2. Feature Flags / Configurations:
• Enable/disable features dynamically based on device, region, or OEM-specific
customizations.
3. Branding and UI Variations:
• Manufacturers use RRO to change default settings or colors for different models.

How RRO Works:


1. Overlay Package Creation:
• A separate APK containing alternative resources is created.
• This APK is installed as an overlay package.
2. Overlay Activation:
• The system links the overlay resources to the target app.
• If an app requests a resource (e.g., a color), the overlay can replace it dynamically.
3. Overlay Priorities:
• Multiple overlays can exist for the same resource.
• The system decides which overlay to apply based on priority.

Example of RRO Implementation:


1. Define an Overlay APK:
• Create a new module in Android Studio.
• Define alternative resources in res/values/colors.xml:

<resources
xmlns:android="http://schemas.android.com/apk/res/android">
<color name="primary_color">#FF0000</color> <!-- Overrides the
original color -->
</resources>

• Set AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.overlay">
<overlay android:targetPackage="com.example.targetapp"
android:priority="1"
android:isStatic="true" />
</manifest>

2. Activate the Overlay Using ADB:

adb shell cmd overlay enable com.example.overlay

3. Verify the Overlay:

adb shell cmd overlay list

Key Advantages of RRO:


• No need to modify the APK (separates customization from base app).
• OEMs and system apps can dynamically modify UI without new builds.
• Used for theming and configuration management in Android devices.

1. What is a Static Overlay?


A Static Overlay is a prebuilt resource override that is applied at the time of system compilation.
This means the overlay is already present when the system boots, and it cannot be changed at
runtime.
When to Use Static Overlays?
• When the resource modification is permanent and should be available from boot.
• When the overlay should not be disabled or modified at runtime.
• Used in system-level customization (OEM themes, vendor-specific modifications).

Example Use Case for Static Overlay


Changing the default status bar background color in AOSP
• Assume you want to change the status bar color from default black to blue for all devices.
• Since this should be enforced always, a static overlay is the right choice.

2. What is a Runtime Overlay?


A Runtime Overlay is an overlay package that can be dynamically enabled or disabled while the
system is running using Overlay Manager Service (OMS).

When to Use Runtime Overlays?


• When the resource modification should be dynamic (e.g., user themes, night mode).
• When multiple variations of a resource should be available (e.g., light mode, dark mode).
• When modifications should be toggleable without requiring a system reboot.

Android Architecture
1. Linux Kernel Layer
• Android is built on Linux Kernel, which provides:
• Process Management (Scheduling, Threading)
• Memory Management
• Security (SELinux, Permissions)
• Driver Support (Display, Camera, Audio, Bluetooth, Wi-Fi)
• Power Management (Wake Locks, Battery Management)
• Networking (TCP/IP, VPN, Wi-Fi, Mobile Data)
• Important Kernel Subsystems:
• Binder IPC Mechanism (for inter-process communication)
• Low Memory Killer (LMK) (for handling OOM scenarios)

2. Hardware Abstraction Layer (HAL)


• Acts as a bridge between Kernel and Framework.
• Defines standard C++ interfaces for hardware functionalities like:
• Camera (camera HAL)
• Audio (audio HAL)
• Sensors (sensor HAL)
• Graphics (gralloc, OpenGL)
• Bluetooth (bluetooth HAL)
• Wi-Fi (wifi HAL)
• Implemented using HIDL (HAL Interface Definition Language) or AIDL (Android Interface
Definition Language).

3. Native Libraries & Android Runtime (ART)


This layer contains C/C++ system libraries and Android Runtime (ART/Dalvik VM).

A. Native Libraries
• Written in C/C++, these libraries provide core features like:
• SurfaceFlinger (Graphics rendering using OpenGL)
• Media Framework (Playback and Recording)
• WebKit (Web rendering)
• SQLite (Database)
• Libc (Standard C library)
• SSL (Security libraries)

B. Android Runtime (ART)


• ART (Android Runtime) replaces Dalvik VM (since Android 5.0 Lollipop).
• Uses Ahead-of-Time (AOT) Compilation instead of Just-in-Time (JIT).
• Supports Garbage Collection (GC), Performance Optimizations, and Profile-Guided
Compilation (PGC).
• Runs Java/Kotlin apps via compiled bytecode.

4. Framework Layer
The Framework Layer in Android acts as a bridge between the Android Runtime and the Native
System components. It includes:
1. Java APIs – Provide interfaces for app developers to interact with system services (e.g.,
ActivityManager, WindowManager, PowerManager).
2. JNI (Java Native Interface) – Allows Java code to communicate with native C/C++ libraries
(used for performance-critical operations and hardware interaction).
3. Core Platform Services (System Services) – Essential services running in SystemServer that
manage app lifecycle, power, input, display, telephony, etc.

5. Application Layer
• Topmost layer, contains:
• System Apps: Phone, Messages, Settings, Contacts.
• User Apps: Installed by users from Play Store.
• OEM specific Apps: Pre-installed, provided by the vendors.
• These apps interact with Framework APIs to access system resources.

Android Boot-Up Sequence


The Android boot-up sequence is the process by which an Android device powers on and loads the
operating system. It involves multiple stages, from initializing hardware to starting system services
and the UI.

1. Overview of Android Boot Process


When an Android device is powered on, it goes through the following boot stages:
1. Boot ROM → Executes from a hardware chip to verify and load the bootloader.
2. Bootloader → Initializes hardware components and loads the Linux kernel.
3. Kernel Initialization → Sets up memory, drivers, and the root filesystem.
4. Init Process → Mounts partitions and starts system services.
5. Zygote & System Server → Launches core system processes and prepares the UI.
6. Home Screen & User Interaction → The device is now fully operational.
2. Detailed Boot-Up Process
2.1 Boot ROM (First Stage) - Hardware Initialization
What is Boot ROM?
• The first code executed when the device is powered on.
• It is stored in the processor’s ROM and cannot be modified.
• Responsible for verifying and loading the bootloader from storage.

Steps in Boot ROM Stage:


1. Performs hardware integrity checks.
2. Searches for the bootloader in internal storage (eMMC/UFS).
3. Verifies bootloader authenticity using cryptographic validation.
4. If verification fails, the device enters Recovery Mode or Failsafe Mode.

Example:
When you power on a device, Boot ROM ensures that the bootloader is authentic before
proceeding.

2.2 Bootloader (Second Stage) - Setting Up the System


What is the Bootloader?
• A small program stored in flash memory responsible for loading the OS.
• Initializes CPU, RAM, and essential peripherals.
• Allows entry into Fastboot Mode for flashing firmware.

Steps in Bootloader Stage:


1. Initializes the CPU, RAM, and display hardware.
2. Determines which boot partition to load:
• Normal Boot → Loads the Android OS.
• Recovery Mode → Boots into recovery for troubleshooting.
• Fastboot Mode → Used for flashing firmware.
3. Loads the Linux kernel and transfers control to it.

Example:
Holding Volume Down + Power boots into Fastboot Mode, where firmware can be flashed via
fastboot commands.

2.3 Kernel Initialization (Third Stage) - Loading the Operating System


What is the Kernel?
• The Linux kernel is the core of the Android OS.
• It acts as an interface between hardware and software, managing processes, memory, and
drivers.
Steps in Kernel Initialization Stage:
1. Initializes memory management, CPU scheduling, and hardware drivers.
2. Mounts the root filesystem (initramfs).
3. Loads essential device drivers (WiFi, touchscreen, storage, etc.).
4. Starts the first user-space process: init.

Example:
If the kernel fails to initialize correctly, the device may get stuck in a boot loop or show a kernel
panic error.

2.4 The init Process (Fourth Stage) - Starting System Services


What is init?
• First user-space process executed after the kernel is loaded.
• Responsible for mounting partitions, setting up the system, and launching essential services.

Steps in Init Stage:


1. Reads the init.rc script, which contains startup instructions.
2. Mounts system partitions (/system, /data, /vendor).
3. Starts system services, such as:
• ADB (Android Debug Bridge) for debugging.
• Logging daemons (logd, servicemanager).
4. Prepares the runtime environment, including Zygote and the Android framework.

2.5 Zygote, System Server & User Interface (Fifth Stage) - Starting Android
Framework
What is Zygote?
• Zygote is the first Dalvik/ART VM process, responsible for launching app processes.
• Every app is forked from Zygote, reducing memory usage and improving performance.

Steps in Zygote & System Server Stage:


1. Zygote Process Starts
• Loads system libraries and preloads common app resources.
• Forks new processes for app execution.
2. System Server Starts
• Launches core Android services, including:
• Activity Manager → Manages app lifecycle.
• Window Manager → Handles UI and animations.
• Package Manager → Manages installed apps.
3. Boot Animation & UI Initialization
• SurfaceFlinger starts, which handles graphics rendering.
• The boot animation plays until the system is ready.
• The home screen appears, allowing user interaction.
Android Treble Architecture
Project Treble was introduced in Android 8 (Oreo) to improve the update process by modularizing
the Android OS framework from vendor-specific implementations.

Why Was Treble Introduced?


Before Treble, Android updates were slow because manufacturers had to update both their own
code and the core Android framework. Treble separates the Android framework from the vendor-
specific code, making updates faster and easier.

Treble Architecture Layers

Android Treble divides the architecture into two major parts:


1. Android OS Framework (Generic System Image - GSI)
• This includes the core Android components and APIs provided by Google.
• Can run independently of vendor-specific code.
2. Vendor Implementation (Vendor Partition)
• Includes hardware drivers, HALs (Hardware Abstraction Layer), and vendor-specific
customizations.
• This part is maintained by chipset manufacturers like Qualcomm, MediaTek,
Samsung, etc.

Key Components in Treble


1. Vendor Interface (VINTF - Vendor Interface Object)
• Defines a strict interface between the OS framework and vendor code.
• Uses HIDL (HAL Interface Definition Language) to communicate with HALs.
• Ensures the framework can be updated independently without affecting vendor
components.
2. HIDL (Hardware Abstraction Layer Interface Definition Language)
• Standardizes communication between the Android framework and hardware.
• Replaces the old AIDL-based HALs that required recompilation for every update.
• Example: Camera, Bluetooth, Audio, Wi-Fi all use HIDL interfaces.
3. VNDK (Vendor Native Development Kit)
• A set of shared libraries that vendor components use to interact with the Android OS.
• Ensures backward compatibility for vendor-specific implementations.
4. GSI (Generic System Image)
• A pure AOSP build of Android that can run on any Treble-compliant device.
• Allows testing newer Android versions without modifying vendor components.
• Example: Google requires GSI to be bootable on all Treble-compliant devices.
Make-Based Build System

Building an android syatem is a very complex process that involves compiling and linking of
thousands of files.
Make is the build automation tool that is used to build android systems. Make uses a file make file
to the build process. Makefile specifies how to build the target system, its dependencies and the
required commands.

Example Android.mk File


LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := libexample
LOCAL_SRC_FILES := example.cpp
LOCAL_CFLAGS := -Wall
LOCAL_SHARED_LIBRARIES := liblog libc
LOCAL_STATIC_LIBRARIES := libbase
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_MODULE_TAGS := optional

include $(BUILD_SHARED_LIBRARY)

Important Flags in Android.mk

LOCAL_PATH Sets the base path for the module files.


LOCAL_MODULE Defines the name of the module (must be unique).
LOCAL_SRC_FILES Lists source files to be compiled.
LOCAL_CFLAGS Compiler flags for C/C++ source files.
LOCAL_CPPFLAGS Additional compiler flags for C++ files.
LOCAL_LDFLAGS Linker flags for the module.
LOCAL_STATIC_LIBRARIE
S Specifies static libraries to be linked.
LOCAL_SHARED_LIBRARIE
S Specifies shared libraries to be linked.
LOCAL_MODULE_TAGS Defines tags such as debug, eng, or tests.
LOCAL_C_INCLUDES Specifies additional include directories.
LOCAL_REQUIRED_MODULE
S Ensures other modules are built before this one.
LOCAL_PREBUILT_LIBS Includes prebuilt libraries instead of compiling from source.
LOCAL_MODULE_PATH Defines the installation path for the module.
Specifies whether the module is built for 32-bit, 64-bit, or
LOCAL_MULTILIB
both.
LOCAL_INIT_RC Specifies .rc files to be included.
LOCAL_VENDOR_MODULE Marks the module as a vendor component.
Soong Based Build System
Soong is a build system used to build android system it is used to replace old make based build
system. It reduces the build complexity and it is more maintainable and scalable.
It uses the .bp files in build process which is the replacement of .mk files.

The soong build system parces through the .bp files and creates a single build.ninja file that contains
all build instructions for building the target system. This build.ninja file is given to ninja.

Ninja i s build execution tool that is used to process build instructions for building a system. It
compiles the source code, links the dependencies and generates the binaries.

Example Android.bp File


bp

cc_library_shared {
name: "libexample",
srcs: ["example.cpp"],
cflags: ["-Wall"],
shared_libs: ["liblog", "libc"],
static_libs: ["libbase"],
include_dirs: ["include"],
host_supported: true,
}

Important Flags in Android.bp


Flag Definition
name Defines the module name (must be unique).
srcs Specifies source files to compile.
cflags Specifies compiler flags for C/C++ source files.
cppflags Additional flags for C++ source files.
ldflags Specifies linker flags for the module.
include_dirs Specifies directories to search for header files.
static_libs Lists static libraries to be linked.
shared_libs Lists shared libraries to be linked dynamically.
runtime_libs Lists runtime dependencies required for execution.
defaults Inherits properties from another module.
required Ensures other modules are built before this one.
host_supported Allows module to be built for host (PC) instead of target (Android device).
device_supporte
d Allows module to be built for Android device.
Flag Definition
product_specifi
c Marks the module as product-specific.
vendor Marks the module as a vendor component.
recovery Marks the module as available in recovery mode.
ramdisk Marks the module as available in RAM disk.

Log Analysis and Logcat in Android


Overview of Log Analysis in Android
Log analysis is a critical part of debugging and troubleshooting Android applications and system
behavior. The Android system provides a logging framework that allows developers to capture,
filter, and analyze logs generated by applications, system services, and the kernel.
The primary tool for log analysis in Android is Logcat, which captures and displays logs from
different components in real time. These logs help developers identify issues related to app crashes,
performance bottlenecks, ANRs (Application Not Responding), and system-level failures.

What is Logcat?
Logcat is a command-line tool that collects and displays logs from an Android device or emulator. It
provides insights into:
• Application behavior
• System processes and services
• Kernel logs
• Hardware-related messages (e.g., radio, Wi-Fi, Bluetooth)

How to Access Logcat


1. Through Android Studio:
• Open Android Studio.
• Click on View → Tool Windows → Logcat.
• Select the connected device/emulator.
• Use filters to search for logs based on tags, process IDs, or severity levels.
2. Using ADB (Android Debug Bridge):
• Run the following command:
sh
adb logcat
• To save logs to a file:
sh
adb logcat -d > log_output.txt

Log Buffers in Logcat


Android maintains multiple log buffers, each serving a different purpose. The four main log buffers
are:

1. Main Buffer (main)


• Stores application logs (logs from apps that use Log.d, Log.i, Log.e, etc.).
• Contains logs printed by applications using the android.util.Log class.
• Helpful for debugging application behavior, crashes, or unexpected states.

Commands to View Main Logs


sh
adb logcat -b main

To filter logs for a specific tag:


sh
adb logcat -b main MyAppTag:D *:S

2. System Buffer (system)


• Stores logs generated by system services and framework components.
• Includes logs related to system-level operations like:
• Activity lifecycle events
• Power management
• Background services
• System-level broadcast receivers

Commands to View System Logs


sh
adb logcat -b system

3. Event Buffer (events)


• Stores logs for system-wide events, such as:
• Activity lifecycle events (created, paused, resumed, etc.)
• Garbage Collection (GC) events
• System performance-related events
• App start and stop events
• Logged using android.util.EventLog.
Commands to View Event Logs
sh
adb logcat -b events

To filter logs for Activity Manager (AM) events:


sh
adb logcat -b events | grep am_

4. Radio Buffer (radio)


• Stores logs related to network, telephony, and modem.
• Includes logs for:
• SIM card detection
• Cellular network connectivity
• Call and SMS events
• Airplane mode changes

Commands to View Radio Logs


adb logcat -b radio

Log Level Description


V (Verbose) Logs everything, including debugging info.
D (Debug) Logs debugging messages.
I (Info) Logs general system information.
W (Warning) Logs warnings about potential issues.
E (Error) Logs errors and crashes.

adb logcat *:E

Debugging: Bugreport & Issue Analysis (ANR, Tombstone,


Watchdog, Force Closure)
This documentation provides a structured approach to debugging critical Android issues using
bugreport, with detailed steps for analyzing ANRs, tombstones, watchdog timeouts, and force
closures.

1. Bugreport: What It Is & How to Generate It


A bugreport is a comprehensive system log that captures device information, running processes,
error logs, and system failures. It helps diagnose issues such as app crashes, ANRs, watchdog
timeouts, and native process failures.
1.1 Generating a Bugreport
To generate a bugreport, use the following ADB (Android Debug Bridge) commands:

Full Bugreport (ZIP format)

adb bugreport bugreport.zip

Quick Bugreport (Terminal Output)

adb shell bugreport

Save Bugreport as Text File

adb bugreport > bugreport.txt

Extract Specific Logs

adb logcat -b system -b main -b radio -b events -d > log.txt

Extract System Properties

adb shell getprop

2. Issue Analysis

2.1 ANR (Application Not Responding)


What is an ANR?
An ANR occurs when an application fails to respond within 5 seconds (foreground app) or 10
seconds (background service). Android then displays a "Wait" or "Close App" dialog to the user.

Common Causes of ANRs


• Blocking the main thread (e.g., long database queries, network calls).
• Deadlocks in multi-threaded applications.
• Heavy operations in BroadcastReceivers.
• Slow I/O operations (file read/write delays).

How to Debug an ANR


Step 1: Check traces.txt

adb shell cat /data/anr/traces.txt


Find the main thread (tid=1) and identify the function blocking it.

Step 2: Check Logcat for ANR Details

adb logcat -b system -b main | grep "ANR"

This shows which app and function caused the ANR.

Step 3: Identify the Blocking Code


• If traces.txt shows a database query or network call, move it to a background thread.
• Look for mutex locks, sleep calls, or infinite loops causing deadlocks.

Fixing ANRs
• Use AsyncTask, Handlers, Executors for background tasks.
• Optimize database queries (use Room, pagination).
• Minimize work in BroadcastReceivers.
• Use WorkManager for background tasks.

2.2 Tombstone (Native Crash Debugging)


What is a Tombstone?
A tombstone is a crash dump generated when a native process crashes due to:
• Memory corruption (SIGSEGV, SIGABRT)
• Stack overflows
• Accessing freed memory (double free)
• JNI errors in native code

How to Debug a Tombstone


Step 1: Extract the Tombstone Log

adb shell ls /data/tombstones/


adb shell cat /data/tombstones/tombstone_XX

This provides details about the crash, including signal type and fault address.

Step 2: Analyze the Fault Address


Look for a crash signal like:
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0xdeadbeef

• SIGSEGV → Invalid memory access (segmentation fault).


• SIGABRT → Process aborted due to memory corruption.

Step 3: Grep the Process ID (PID) and Thread ID (TID)

ps | grep <package_name>
This finds the process running the crashed code.

Step 4: Attach Process to GDB Client

gdbserver :5039 --attach <pid>

Use gdbclient to debug the process in real-time.

Step 5: Set Breakpoints and Backtrace the Function Call

break <function_name>
bt

• bt (backtrace) shows the function call history before the crash.


• Use info registers to check memory and register states.

Step 6: Analyze Memory and Registers

info registers
x/10x <fault_address>

Check for memory corruption or invalid addresses.

Fixing Native Crashes


• Avoid null pointer dereferences.
• Free memory properly (prevent double free errors).
• Use addr2line to map crash addresses to source code.

addr2line -e your_library.so 0xdeadbeef

• Check for race conditions in multi-threaded code.

2.3 Watchdog (System Server Crashes)


What is a Watchdog Timeout?
The Watchdog service kills and restarts the SystemServer process if it remains unresponsive for 60
seconds.

Common Causes of Watchdog Timeouts


• Deadlocks in system services.
• Long-running operations in main system threads.
• Blocked Binder transactions.
• Excessive CPU load causing system slowdowns.
How to Debug Watchdog Issues
Step 1: Check Logcat for Watchdog Logs

adb logcat -b system | grep "watchdog"

Look for:
E Watchdog: SystemServer is not responding, rebooting...

Step 2: Analyze CPU and Memory Usage

adb shell dumpsys cpuinfo


adb shell dumpsys meminfo

Find which process is using excessive CPU/memory.

Fixing Watchdog Issues


• Move heavy tasks to background threads.
• Optimize IPC (Binder transactions) to avoid timeouts.
• Use StrictMode to detect long-running main-thread operations.

2.4 Force Closure (App Crashes)


What Causes Force Closures?
• NullPointerException
• ArrayIndexOutOfBoundsException
• SecurityException (missing permissions)
• JNI errors in native code

How to Debug Force Closures


Step 1: Check Logcat for Crash Logs

adb logcat -b main | grep "FATAL EXCEPTION"

Step 2: Identify the Stack Trace


• Find the crashing function and exception type.
• If it's an NPE, ensure variables are initialized before use.

Fixing Force Closure Issues


• Use try-catch blocks to handle exceptions.
• Check for null values before accessing objects.
• Request necessary permissions before accessing restricted APIs.
Inter-Process Communication (IPC) in Android

What is IPC in Android?


In Android, Inter-Process Communication (IPC) is required when two different processes need to
communicate with each other. Since Android follows a sandboxed architecture, each application
runs in its own process with its own memory. This means one app cannot directly access another
app's memory.
To enable communication between different processes, Android provides several IPC mechanisms:
1. Intent (Component-Based IPC)
2. Messenger (One-Way Message-Based IPC)
3. Binder (Two-Way High-Performance IPC using AIDL)

Intent-Based IPC (Lightweight & Simple Communication)


What is an Intent?
An Intent is a messaging object that allows components to communicate within and across
applications. It can be used to:
• Start an Activity in the same app as well as in the another app.
• Start a Service (background process).
• Send Broadcasts to other applications.

When to Use Intents for IPC?


When passing small, lightweight data (strings, numbers, URIs).
When launching a component (Activity, Service, BroadcastReceiver).
When sending a broadcast message to multiple apps.

Types of Intent-Based IPC

Explicit Intent (Targeting a Specific Component)


Implicit Intent (Let System Choose the Best Component)
Broadcast Intent (Send Messages Across Apps)

Type of Intent Use Case Example


Explicit Intent Start a specific Activity Open HomeActivity from LoginActivity
Implicit Intent Open any app that can handle the action Open a URL in a browser
Broadcast Intent Send system-wide messages Detect network changes
Messenger-Based IPC (One-Way Message Queue)
What is Messenger in Android?
A Messenger is a lightweight IPC mechanism that allows communication between a single client
and a service using a message queue. It is built on the Binder framework but simplifies the
communication model.

When to Use Messenger for IPC?

When a single client communicates with a service.


When communication involves simple messages (e.g., requests, commands).

How Messenger IPC Works

Key Components
Component Description
Messenger A wrapper around Handler that facilitates IPC.
Handler Processes messages in the service thread.
Message Encapsulates data sent between processes.
MessageQueue Stores messages and delivers them sequentially.

How Data Flows in Messenger IPC


1️) The Client creates a Messenger and sends a Message to the Service.
2) The Message is added to the Service’s MessageQueue.
3️) The Service's Handler processes the Message asynchronously.

Scenario:
Suppose we are building a music player app, where a client (Activity) sends commands (play,
pause, stop) to a background service that plays music. The service should process requests one at a
time and respond accordingly.

Binder IPC in Android – In-Depth Explanation


1. What is Binder IPC?
Binder is the primary Inter-Process Communication (IPC) mechanism in Android. It allows
processes (apps, system services, etc.) to communicate efficiently and securely.
2. Key Components of Binder IPC
Binder IPC involves multiple components:

Component Description
Client (Caller Process) The process that wants to communicate with another process.
Service (Callee Process) The process providing the functionality (e.g., Location Service).
Binder The underlying mechanism that enables IPC.
IBinder An interface that facilitates communication between client and service.
ServiceManager Manages system services and their registration.

3. How Binder Works – Step-by-Step Flow


Use Case: Fetching Battery Percentage from System Service
1️) The client (app) wants the battery level.
2️) The client calls a method on a remote interface (IBinder).
3️) The request is sent via Binder to the Battery Service.
4️) The Battery Service processes the request and responds with the battery level.
5️) The client receives the response.

Comparison of Intent, Messenger, and Binder

Feature Intent Messenger Binder (AIDL)


Messages (Message Any data (Objects, Complex
Data Type Small data (Strings, Ints)
objects) types)
Direction One-way One-way Two-way
Performance Slow Medium Fast
Launching components, Complex communication
Best Use Case Simple messaging
sending broadcasts between services
Complexity Low Medium High

Inter-Process Communication (IPC) through AIDL in Android

What is AIDL?
AIDL (Android Interface Definition Language) is a mechanism in Android used for Inter-Process
Communication (IPC). It allows processes running in different memory spaces to communicate by
defining an interface that clients and services can use to send data across processes.
In simpler terms, if one Android app (or a service running in the background) needs to send data to
another process, AIDL provides a structured way to do this.

Why Use AIDL?

AIDL (Android Interface Definition Language) is required when different applications or processes
need to communicate efficiently in real-time. Since Android runs apps in separate processes for
security and stability, direct method calls don’t work across processes. AIDL helps by enabling fast,
structured, two-way communication between different processes using IPC (Inter-Process
Communication).

Use Cases of AIDL:

When multiple applications or components need access to a single service.


When complex data types (like lists, objects, and custom classes) need to be passed.
When the communication is frequent and performance is critical.

AIDL Workflow

1️) Define an AIDL Interface → Write a .aidl file defining methods.


2️) Implement the AIDL Interface in the Service (Server) → Implement the methods in a Service.
3️) Declare the Service in AndroidManifest.xml → Make the service available for IPC.
4️) Bind to the Service from the Client → The client app connects using bindService().
5️) Use the AIDL Methods → The client calls remote methods, and the server responds.

Use Case of AIDL (Android Interface Definition Language) IPC


Scenario: Music Player Service Accessed by Multiple Apps
Imagine you are building a music streaming service that runs in the background as a system service.
You want multiple apps (e.g., a music player UI, a voice assistant, and a smart home app) to control
playback, get the current song, or adjust volume, but they are running in different processes.
Since these apps need to communicate with the background music service, AIDL is the best choice
for efficient IPC (Inter-Process Communication).

Use Case Flow


1. Music Service (Runs in the Background)
• This service handles music playback.
• It provides functions like play, pause, stop, getCurrentSong, adjustVolume.
• It runs in a separate process to keep playing even when the UI app is closed.
2. Music Player App (Client App 1)
• This app has a UI where users can play/pause music, skip tracks, and adjust volume.
• It connects to the Music Service via AIDL to send playback commands.
3. Voice Assistant App (Client App 2)
• The voice assistant can say, "Play my favorite song".
• It sends a request to the Music Service via AIDL to start playing a specific song.
4. Smart Home App (Client App 3)
• A smart home app wants to lower the music volume when a doorbell rings.
• It connects to the Music Service via AIDL and calls the adjustVolume() function.

Unlike services that use AIDL-generated interfaces (Stub.asInterface()), PackageManager does not
directly implement Stub.asInterface() because it follows a different approach using Binder
proxies and delegates.

PackageManager is an Abstract API (Client-Side)


• The PackageManager class itself is just an abstract API that is exposed to apps.
• It does not directly communicate with the PackageManagerService.
• Instead, the actual implementation is in ApplicationPackageManager, which
delegates IPC calls to the real PackageManagerService.

ApplicationPackageManager Acts as a Middle Layer


• The real implementation of PackageManager used by apps is
ApplicationPackageManager.
• ApplicationPackageManager acts as a wrapper around an internal system service
(IPackageManager), which does the actual work.

private final IPackageManager mPM;

ApplicationPackageManager(ContextImpl context, IPackageManager pm) {


mContext = context;
mPM = pm; // IPackageManager is the actual system service interface
}

IPackageManager is the Binder Interface


• IPackageManager.aidl defines the actual IPC methods (e.g., getPackageInfo(),
installPackage(), etc.).
• ApplicationPackageManager uses this interface to make IPC calls to
PackageManagerService.
ActivityManager Uses IActivityManager for IPC
Although ActivityManager itself doesn’t call Stub.asInterface(), it internally relies on
ActivityTaskManager, which does!

Inside ActivityManager.java:
java
CopyEdit
private static final IActivityManager getService() {
return IActivityManagerSingleton.get();
}

Android System Server & System Services


What is System Server in Android?
The System Server is one of the most critical components of Android. It is responsible for managing
all the core system services that make the Android OS function smoothly.
System Server is a process (system_server) that starts after the Zygote process forks it.
It runs multiple system services that manage UI, notifications, power, sensors, apps, and more.
It is started by the Zygote process in Android.
All system services run inside the same process (system_server) to avoid IPC overhead.

Android Boot Process & Where System Server Fits In


Before understanding the System Server, let’s briefly look at how Android boots up:
1️) Boot ROM: Hardware initialization starts (executed from a chip).
2️) Bootloader: Loads the Linux kernel into memory.
3️) Kernel: Initializes drivers, mounts the filesystem, and starts init.
4️) init Process: Reads init.rc and starts system services.
5️) Zygote Process: Starts the System Server.
6️) System Server: Starts Android System Services.
7️) Home Launcher: The Android UI appears.
The System Server is started by Zygote and is responsible for running system services.

System Services Are Categorized Into:


Category Examples Purpose
ActivityManagerService, Manages apps, power, and
Core Services
PowerManagerService system states.
Manages audio, video, and
Media Services AudioService, MediaSessionService
media playback.
Category Examples Purpose
Handles Wi-Fi, mobile data,
Connectivity
WifiService, TelephonyRegistry Bluetooth, and network
Services
services.
Hardware Manages sensors and hardware
SensorService, VibratorService
Services peripherals.
WindowManagerService, Handles UI rendering and
UI Services
InputMethodManagerService input methods.

ActivityManagerService (AMS) - Manages Apps & Activities

Role:
Manages activity lifecycle (start, stop, destroy).
Handles app switching and background processes.
Manages process crashes and ANRs (Application Not Responding).
How AMS Works?
Whenever you start an app, ActivityManagerService creates a new process for it.
It tracks all running activities and maintains their state.

WindowManagerService (WMS) - Handles Windows & UI


Role:
Manages windows (activities, dialogs, system overlays).
Handles screen rotation, animations, and touch events.
Controls screen brightness and display properties.

PowerManagerService (PMS) - Controls Power & Battery


Manages screen wake/sleep state.
Controls CPU, GPU, and device power modes.
Handles battery life optimizations.

PackageManagerService (PMS) - Manages Installed Apps


Handles app installation, updates, and removal.
Manages app permissions.
Provides info about installed packages.
Custom System Service Creation in Android (AOSP)

Why Create a Custom System Service?


Extend Android’s functionality (e.g., add a custom hardware API).
Provide system-wide features that apps can use.
Handle background tasks efficiently at the framework level.

Steps to Create a Custom System Service


Step 1: Define AIDL Interface
Since system services interact across processes, we may need AIDL (Android Interface Definition
Language) for IPC.
Location:
Create a new AIDL file in:

frameworks/base/core/java/com/example/customservice/ICustomService
.aidl

package com.example.customservice;

// Define an AIDL interface for the custom service


interface ICustomService {
void setValue(int value);
int getValue();
}

Step 2: Implement the System Service


Location:
Create a new service class in:

frameworks/base/services/core/java/com/example/customservice/Custo
mService.java
java

package com.example.customservice;

import android.os.IBinder;
import android.os.RemoteException;
import android.util.Slog;
import com.android.server.SystemService;

public class CustomService extends SystemService {


private static final String TAG = "CustomService";
private int storedValue = 0;

public CustomService(Context context) {


super(context);
}
@Override
public void onStart() {
Slog.d(TAG, "Custom Service Started");
publishBinderService("custom_service", mBinder);
}

private final ICustomService.Stub mBinder = new ICustomService.Stub() {


@Override
public void setValue(int value) {
storedValue = value;
Slog.d(TAG, "Value set to: " + storedValue);
}

@Override
public int getValue() {
return storedValue;
}
};
}

Step 3: Register the Service in SystemServer


To make our service start at boot, modify SystemServer.java.
Location:
frameworks/base/services/java/com/android/server/SystemServer.java
Find the method startOtherServices() and add:
java

// Start the Custom Service


CustomService customService = new CustomService(context);
ServiceManager.addService("custom_service", customService);

Step 4: Define Service Permission


If the service should only be accessible by privilaged or system apps, define a custom permission.
Location:
frameworks/base/core/res/AndroidManifest.xml
xml

<permission android:name="com.example.customservice.PERMISSION"
android:protectionLevel="signature" />

Init Services in Android


What are Init Services in Android?
Init services in Android are system-level processes defined in init.rc scripts. They are
responsible for starting critical system services and can be triggered dynamically while the system
is running.
Why do we need Init Services?
They have special privileges (root access).
They allow executing operations restricted by SELinux.
They provide a secure way to perform system-level tasks.
Suppose you want to change the Ethernet MAC address from an app, but due to SELinux
restrictions, the system won’t allow it.
Android allows triggering init services dynamically using system properties.
This is done using a special system property:
sh
ctl.start

on property,on boot on post-fs-data etc.

Defining an Init Service in init.rc


Init services are defined in init.rc scripts, which are located in the root file system
(/etc/init/ or /vendor/etc/init/).
These scripts are loaded at boot and define how system services should run.
service my_service /system/bin/my_service
class main
user root
group root
oneshot
seclabel u:r:my_service_label:s0

Keyword Meaning
service my_service Defines a service named my_service that runs
/system/bin/my_service /system/bin/my_service.
Assigns the service to the main class (ensuring it can
class main
be started).
Runs the service as the root user (needed for
user root
privileged operations).
group root Assigns the process to the root group.
oneshot Ensures the service runs only once and doesn’t restart
automatically.
seclabel Sets the SELinux security label (required for security
Keyword Meaning
u:r:my_service_label:s0 enforcement).

Trigerring from native c/c++ codes


#include <cutils/properties.h>
property_set("ctl.start", "my_service:first_arg second_arg");

Trigerring from java codes


import android.os.SystemProperties;
SystemProperties.set("ctl.start", "my_service:first_arg second_arg");

Changing Ethernet MAC Address(use case)


i) define the service in init.rc
service change_mac /system/bin/change_mac.sh
class main
user root
group root
oneshot
seclabel u:r:change_mac:s0

ii) create shell script in system/bin


#!/system/bin/sh
ifconfig eth0 hw ether AA:BB:CC:DD:EE:FF

iii) trigger the service


adb shell setprop ctl.start "change_mac"

SELinux in Android
Security-Enhanced Linux (SELinux) is a mandatory access control (MAC) mechanism integrated
into the Linux kernel. In Android, SELinux enforces security policies that restrict how processes
interact with each other and with system resources.
1. What is SELinux?
SELinux is a security feature in Linux that controls access to files, processes, and system resources
based on security policies.
Enforces strict security policies that prevent unauthorized access.
Works in two modes: Permissive (logs violations) and Enforcing (blocks violations).

2. Why is SELinux Important in Android?


Before SELinux, Android relied on Discretionary Access Control (DAC), where:
Processes could access any file based on owner/group/permissions.
A compromised app could easily access sensitive system files.
With SELinux, even root users cannot bypass security policies.
Benefits of SELinux in Android:
Prevents privilege escalation attacks.
Protects against malware.
Limits damage from security vulnerabilities.
Prevents unauthorized apps from accessing system resources.

3. SELinux Modes in Android


SELinux can operate in two modes:

Mode Behavior Use Case


Permissive Logs violations but doesn’t enforce rules. Used for debugging and testing.
Enforcing Blocks actions that violate policies. Used in production for strict security.

To check SELinux mode on a device:


sh
adb shell getenforce

To switch SELinux to permissive mode (for debugging only):


sh
adb shell setenforce 0 # Permissive
adb shell setenforce 1 # Enforcing

4. SELinux Security Contexts (Labels)


SELinux assigns labels (contexts) to files, processes, and sockets.
A context has four fields:
pgsql
user:role:type:mls_level

📍 Example:
sh
u:r:system_server:s0
Field Meaning Example
User SELinux user u (unprivileged), r (root)
Role SELinux role system_r (system process)
Type Defines what the process/file can do system_server
MLS Level Multi-Level Security (MLS) s0 (default)

Product Configuration in AOSP


Product configuration in AOSP determines how a particular build variant of Android is compiled,
packaged, and deployed. It involves specifying which apps, libraries, and binaries are included, as
well as setting various build flags and properties.

1. Product Makefile
What is a Product Makefile?
A Product Makefile (<product_name>.mk) defines the components and configuration for a
particular Android build product. It specifies:
• Applications to be included
• System properties
• Build flags
• Libraries and binaries to include
• Partition layout configurations

Where is it Located?
• Located in the device/ directory or under vendor/ if it's for a specific vendor.

• Typical path: device/<vendor>/<device_name>/ or


vendor/<vendor_name>/<device_name>/.

Example Directory Structure:


bash
device/google/pixel/
├── Android.mk
├── BoardConfig.mk
├── pixel.mk
├── pixel-product.mk
└── device.mk

Example of a Product Makefile (pixel.mk):


makefile
PRODUCT_NAME := pixel
PRODUCT_DEVICE := pixel
PRODUCT_BRAND := Google
PRODUCT_MODEL := Pixel
PRODUCT_MANUFACTURER := Google

# Include apps specific to this product


PRODUCT_PACKAGES += \
PixelLauncher \
GoogleCamera

# Specify system properties for this product


PRODUCT_PROPERTY_OVERRIDES += \
ro.product.cpu.abi=arm64-v8a \
ro.build.type=user

# Include common product configurations


$(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk)

2. Adding New Apps and Binaries for a Specific Product


To include a new app or binary in a particular product, you need to modify the relevant Product
Makefile.

Example: Adding a New App (MySpecialApp)


1. Place your app under the source tree:
packages/apps/MySpecialApp/
2. Define the app in Android.mk or Android.bp:
makefile
// Android.mk
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := MySpecialApp
LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_PACKAGE_NAME := MySpecialApp
include $(BUILD_PACKAGE)

3. Add the app to your Product Makefile:


makefile
PRODUCT_PACKAGES += MySpecialApp

Example: Adding a New Binary (mybinary)


1. Place your binary under the source tree:
vendor/<vendor_name>/bin/mybinary
2. Define the binary in Android.bp:
makefile
cc_binary {
name: "mybinary",
srcs: ["mybinary.c"],
enabled: true,
}

3. Add the binary to your Product Makefile:


makefile
PRODUCT_PACKAGES += mybinary

Creating Our Own Lunch Target

1. BoardConfig.mk

Located at: target/board/sasken_phone/BoardConfig.mk

This file defines board-specific configurations. The primary focus here is to define the CPU
architecture and WLAN settings for the emulator.

2. device.mk
Located at: target/board/sasken_phone/device.mk

This file includes product-specific device configurations and ensures compatibility with the
goldfish emulator.

3. system_ext.prop
Located at: target/board/sasken_phone/system_ext.prop

This file contains additional system properties for the Sasken phone product.

4. sasken_phone.mk
Located at: target/product/sasken_phone.mk

This is the main Product Makefile defining the Sasken phone product. It inherits common product
configurations and specifies the build details for the sasken_phone product.

Important Points
• Inherits configurations from various system images:
• core_64_bit.mk
• generic_system.mk
• handheld_system_ext.mk
• telephony_system_ext.mk
• aosp_product.mk
• Emulator-specific configurations like emulator_vendor.mk and
emulator_x86_64/device.mk.

5. Changes in AndroidProducts.mk
Located at: target/product/AndroidProducts.mk
Important Points
• Adds $(LOCAL_DIR)/sasken_phone.mk to the list of available product makefiles.

• Includes sasken_phone-userdebug in COMMON_LUNCH_CHOICES for building the


product.

Declaring the App in the Product Makefile


The most common way to add an app to a specific build is by modifying the product’s .mk file.

Example: Adding an App to sasken_phone.mk


makefile
# File: target/product/sasken_phone.mk

# Define the app name


PRODUCT_PACKAGES += MySpecialApp

# Ensure customization makefile is included


$(call inherit-product-if-exists,
device/sasken/os_customization/device-sasken.mk)

Adding an App via device.mk


Another way is to add the app in the device.mk file of a specific device.

Example: Adding an App to device/sasken_phone/device.mk


makefile
# File: device/sasken_phone/device.mk

# Include the app as part of the build


PRODUCT_PACKAGES += MySpecialApp

# Ensure the product build picks up the customization


PRODUCT_SOONG_NAMESPACES += device/sasken/os_customization

Git Commands

SETUP

Configuring user information used across all local repositories.


• git config --global user.name “[firstname lastname]”
Set a name that will be attached to commits and tags.
• git config --global user.email “[valid-email]”
Set an email address that will be associated with each history marker.
SETUP & INIT

Configuring user information, initializing, and cloning repositories.


• git init
Initialize an existing directory as a Git repository.
• git clone [url]
Retrieve an entire repository from a hosted location via URL.

STAGE & SNAPSHOT

Working with snapshots and the Git staging area.


• git status
Show modified files in the working directory, staged for your next commit.
• git add [file]
Add a file as it looks now to your next commit (stage).
• git reset [file]
Unstage a file while retaining the changes in the working directory.
• git diff
Display differences between working directory and the staging area.
• git diff --staged
Display differences between the staging area and the latest commit.
• git commit -m “[descriptive message]”
Commit your staged content as a new commit snapshot.

BRANCH & MERGE

Isolating work in branches, changing context, and integrating changes.


• git branch
List your branches. A * will appear next to the currently active branch.
• git branch [branch-name]
Create a new branch at the current commit.
• git checkout [branch]
Switch to another branch and check it out into your working directory.
• git merge [branch]
Merge the specified branch’s history into the current one.
• git log
Show all commits in the current branch’s history.

SHARE & UPDATE


Retrieving updates from another repository and updating local repos.
• git remote add [alias] [url]
Add a git URL as an alias.
• git fetch [alias]
Fetch all branches from the specified remote repository.
• git merge [alias]/[branch]
Merge a remote branch into your current branch to bring it up to date.
• git push [alias] [branch]
Transmit local branch commits to the remote repository.
• git pull
Fetch and merge changes from the tracking remote branch.

TEMPORARY COMMITS
Temporarily store modified, tracked files to change branches.
• git stash
Save modified and staged changes.
• git stash list
List stack-order of stashed file changes.
• git stash pop
Apply changes from the top of stash stack.
• git stash drop
Discard the changes from the top of stash stack.

REWRITE HISTORY
Rewriting branches, updating commits, and clearing history.
• git rebase [branch]
Apply any commits of the current branch ahead of the specified one.
• git reset --hard [commit]
Clear staging area, rewrite working tree from the specified commit.

Linux Command Overview

1. ls
Description: Lists files and directories in the current directory.
Example: ls
2. pwd
Description: Prints the current working directory.
Example: pwd

3. cd
Description: Changes the current directory.
Example: cd /home/user/Downloads

4. cp
Description: Copies files or directories.
Example: cp file1.txt file2.txt

5. rm
Description: Removes files or directories.
Example: rm file1.txt

6. mv
Description: Moves or renames files or directories.
Example: mv oldfile.txt newfile.txt

7. mkdir
Description: Creates a new directory.
Example: mkdir newdir

8. man
Description: Displays the manual or help documentation for a command.
Example: man ls

9. touch
Description: Creates an empty file or updates the timestamp of an existing file.
Example: touch newfile.txt

10. chmod
Description: Changes file permissions.
Example: chmod u+rwx script.sh

11. sudo
Description: Executes a command as a superuser (administrator).
Example: sudo apt-get install vim

12. exit
Description: Exits the current shell session.
Example: exit

13. shutdown
Description: Shuts down or reboots the system.
Example: sudo shutdown now

14. top
Description: Displays running processes and system resource usage.
Example: top

16. grep
Description: Searches for patterns in files.
Example: grep "error" logfile.txt

17. zip/unzip
Description: Compresses or extracts compressed files.
Example: zip -r archive.zip myfolder
unzip archive.zip

18. echo
Description: Displays a line of text or a variable value.
Example: echo "Hello World"

19. cat
Description: Displays the contents of a file.
Example: cat file.txt

20. ps
Description: Displays information about running processes.
Example: ps aux

21. kill
Description: Sends a signal to a process, often used to terminate it.
Example: kill 1234
23. history
Description: Displays a list of previously executed commands.
Example: history 10

24. which
Description: Displays the path of a command.
Example: which lunch

25. whereis
Description: Locates the binary, source, and manual pages for a command.
Example: whereis gcc

26. type
Description: Displays information about a command (whether it is a built-in shell command, alias,
or external command).
Example: type ls

27. more/less
Description: Views file contents one page at a time.
Example: more largefile.txt
less largefile.txt

28. head/tail
Description: Displays the beginning or the end of a file.
Example: head file.txt
tail file.txt

29. id/whoami
Description: Displays the user ID or current logged-in user.
Example: id
whoami

30. wc
Description: Counts lines, words, and characters in a file.
Example: wc -l file.txt

31. uname
Description: Displays system information like kernel version and machine hardware.
Example: uname -r
32. find
Description: Searches for files and directories.
Example: find . -name "*.txt"

35. alias
Description: Creates a shortcut or alias for a command.
Example: alias ll="ls -l"

36. date
Description: Displays or sets the system date and time.
Example: date

37. insmod
Description: Inserts a module into the Linux kernel.
Example: sudo insmod module.ko

38. rmmod
Description: Removes a module from the Linux kernel.
Example: sudo rmmod module

39. lsmod
Description: Displays the list of loaded kernel modules.
Example: lsmod

40. gcc/make
Description: Compiler for C programs and builds executables.
Example: gcc hello.c -o hello
make

You might also like