ios反调试之sysctl



http://www.coredump.gr/articles/ios-anti-debugging-protections-part-2/

In the previous part (iOS Anti-Debugging Protections: Part 1) we discussed about ptrace and how it can be used to prevent a debugger from attaching to a process. This post describes a technique that is commonly used to detect the presence of a debugger. Note that unlike the ptrace technique this method doesn’t prevent a debugger from attaching to a process. Instead, it uses the sysctl function to retrieve information about the process and determine whether it is being debugged. Apple has an article in their Mac Technical Q&As with sample code that uses this method: Detecting the Debugger

The sysctl call is defined as:

int sysctl( int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp, size_t newlen);

The first argument name is an array of integers that describe the type of information we are requesting. Apple describes this name as a “Management Information Base” (MIB) style name in the sysctl man page. The second argument contains the number of integers in the name array. The third and fourth arguments hold the output buffer and the output buffer size respectively. These arguments will be populated with the requested information when the function returns. Arguments five and six are only used when setting information.

The following block of code contains an example C program that uses a sysctl call to determine whether it is being debugged. The next paragraphs contain an analysis of the protection as well as information on how to bypass it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sysctl.h>
#include <stdlib.h>
  
static int is_debugger_present( void )
{
     int name[4];
     struct kinfo_proc info;
     size_t info_size = sizeof (info);
  
     info.kp_proc.p_flag = 0;
  
     name[0] = CTL_KERN;
     name[1] = KERN_PROC;
     name[2] = KERN_PROC_PID;
     name[3] = getpid();
  
     if (sysctl(name, 4, &info, &info_size, NULL, 0) == -1) {
         perror ( "sysctl");
         exit (-1);
     }
     return ((info.kp_proc.p_flag & P_TRACED) != 0);
}
  
int main ( int argc, const char * argv[])
{
     printf ( "Looping forever" );
     fflush (stdout);
     while (1)
     {
         sleep(1);
         if (is_debugger_present())
         {
             printf ( "Debugger detected! Terminating...\n" );
             return -1;
         }
         printf ( "." );
         fflush (stdout);
     }
     return 0;
}

The call to sysctl is on line 20:

sysctl(name, 4, &info, &info_size, NULL, 0)

First, lets analyze the arguments of the sysctl call. The first argument name is initialized as:

name[0] = CTL_KERN;
name[1] = KERN_PROC;
name[2] = KERN_PROC_PID;
name[3] = getpid();

The item at index 0 is set to CTL_KERN. This is the top-level name for kernel-specific information. All the available top-level names have a prefix of “CTL_” and are defined in the header file /usr/include/sys/sysctl.h. The item at index 1 is set to KERN_PROC. This indicates that sysctl will return a struct with process entries. The next item KERN_PROC_PID specifies that the target process will be selected based on a process ID (PID). Finally, the last item is the PID of that process.

The second argument of sysctl (size) is set to 4 since this is the total number of items in the name. Arguments three and four are set to the output buffer and its size. The output buffer is a struct of type kinfo_proc which is defined in /usr/include/sys/sysctl.h. The struct contains another struct (kp_proc) of type extern_proc that is defined in /usr/include/sys/proc.h. The kp_proc struct contains information about the process including a flag (p_flag) that describes the process state. All the valid values for p_flag can be found in /usr/include/sys/proc.h. The following block contains some sample values from that file:

#define P_TIMEOUT       0x00000400 
#define P_TRACED        0x00000800 
#define P_DISABLE_ASLR  0x00001000 

The P_TRACED value is set when the process is being debugged. The following line of code in the sample program checks if the value is set:

return ((info.kp_proc.p_flag & P_TRACED) != 0);

Bypassing the sysctl check

This type of check can be bypassed by clearing the contents of the p_flag variable after the call returns. The following paragraphs contain step-by-step instructions on how to accomplish that with the help of GDB.

First, load the application in GDB:

tl0gic:~ mobile$ gdb ./sysctl
Reading symbols for shared libraries . done
(gdb)

Setup a conditional breakpoint on sysctl:

(gdb) break sysctl if $r1==4 && *(int *)$r0==1 && *(int *)($r0+4)==14 && *(int *)($r0+8)==1

This breakpoint will be triggered only if the size argument of sysctl (in $r1) has a value of 4 and the first three items in the name array (at addresses $r0, $r0+4, and $r0+8) are equal to CTL_KERN (1), KERN_PROC (14) and KERN_PROC_PID (1).

Run the process until the breakpoint is hit:

(gdb) run
Starting program: /private/var/mobile/sysctl
Reading symbols for shared libraries ...................... done
Looping forever
Breakpoint 1, 0x35b60672 in sysctl ()
(gdb)

Save the value of $r2, this is the address of output buffer where sysctl will store the process information: (gdb) set $pinfo=$r2

Continue executing until the sysctl call is complete:
(gdb) finish
Run till exit from #0  0x35b60672 in sysctl ()
0x00002ed6 in is_debugger_present ()
(gdb)

Before we continue to the next step we need to setup a breakpoint at the end of sysctl. We will use that breakpoint later to automate this process (don’t worry about the breakpoint condition for now):

(gdb) break *$pc if $pinfo!=-1

Now we need to find the exact offset of the p_flag value inside the output buffer. There are two ways to accomplish that:

  1. Sum the bytes for each of the struct elements that precede the p_flag
  2. Disassemble the sample application and find how the compiler calculates it.

We will go with the second option. The following block contains the disassembly for the is_debugger_present function:

_is_debugger_present:
00002e68        b580    push    {r7, lr}
00002e6a        466f    mov r7, sp
00002e6c    f5ad7d05    sub.w   sp, sp, #532    @ 0x214
00002e70    f24010c0    movw    r0, 0x1c0
00002e74    f2c00000    movt    r0, 0x0
00002e78        4478    add r0, pc
00002e7a        6800    ldr r0, [r0, #0]
00002e7c        6800    ldr r0, [r0, #0]
00002e7e        9084    str r0, [sp, #528]
00002e80        2001    movs    r0, #1
00002e82    f2c00000    movt    r0, 0x0
00002e86        210e    movs    r1, #14
00002e88    f2c00100    movt    r1, 0x0
00002e8c        2200    movs    r2, #0
00002e8e    f2c00200    movt    r2, 0x0
00002e92    f24013ec    movw    r3, 0x1ec
00002e96    f2c00300    movt    r3, 0x0
00002e9a        9304    str r3, [sp, #16]
00002e9c        9209    str r2, [sp, #36]
00002e9e        9080    str r0, [sp, #512]
00002ea0        9181    str r1, [sp, #516]
00002ea2        9082    str r0, [sp, #520]
00002ea4    f000e8a2    blx 0x2fec  @ symbol stub for: _getpid
00002ea8        2104    movs    r1, #4
00002eaa    f2c00100    movt    r1, 0x0
00002eae        ab04    add r3, sp, #16
00002eb0        2200    movs    r2, #0
00002eb2    f2c00200    movt    r2, 0x0
00002eb6    f10d0914    add.w   r9, sp, #20 @ 0x14
00002eba    f50d7c00    add.w   ip, sp, #512    @ 0x200
00002ebe        9083    str r0, [sp, #524]
00002ec0        4660    mov r0, ip
00002ec2        9203    str r2, [sp, #12]
00002ec4        464a    mov r2, r9
00002ec6    f8dd900c    ldr.w   r9, [sp, #12]
00002eca    f8cd9000    str.w   r9, [sp]
00002ece    f8cd9004    str.w   r9, [sp, #4]
00002ed2    f000e894    blx 0x2ffc  @ symbol stub for: _sysctl
00002ed6    f1100f01    cmn.w   r0, #1  @ 0x1
00002eda        d10c    bne.n   0x2ef6
00002edc    f24000f1    movw    r0, 0xf1
00002ee0    f2c00000    movt    r0, 0x0
00002ee4        4478    add r0, pc
00002ee6    f000e884    blx 0x2ff0  @ symbol stub for: _perror
00002eea    f64f70ff    movw    r0, 0xffff
00002eee    f6cf70ff    movt    r0, 0xffff
00002ef2    f000e878    blx 0x2fe4  @ symbol stub for: _exit
00002ef6    f240103a    movw    r0, 0x13a
00002efa    f2c00000    movt    r0, 0x0
00002efe        4478    add r0, pc
00002f00        6800    ldr r0, [r0, #0]
00002f02        9909    ldr r1, [sp, #36]
00002f04    f4016100    and.w   r1, r1, #2048   @ 0x800
00002f08        6800    ldr r0, [r0, #0]
00002f0a        9a84    ldr r2, [sp, #528]
00002f0c        4290    cmp r0, r2
00002f0e        9102    str r1, [sp, #8]
00002f10        d103    bne.n   0x2f1a
00002f12        9802    ldr r0, [sp, #8]
00002f14    f50d7d05    add.w   sp, sp, #532    @ 0x214
00002f18        bd80    pop {r7, pc}

At 0x2eb6 the base address of the kinfo_proc struct is calculated as $sp+20 and loaded in $r9. Then, at 0x2ec4 the address is copied into $r2 (the third argument of sysctl). Once the sysctl call (at 0x2f02) has returned the p_flag value is loaded as $sp+36. Therefore, the offset of the p_flag is $sp+20-($sp+36) = 16 bytes. However, $r2 contains the address of the kinfo_struct and not the actual contents. To access the value of the p_flag we will have to use a pointer as illustrated below:

(gdb) printf "0x%x\n", *(int *)($pinfo+16)
0x5802

The value of P_TRACED is 0×800. Therefore, a logical end with the current value should return 0×800 (or 2048 in base 10) when the flag is set:

(gdb) print (*(int *)($pinfo+16) & 0x800)
$5 = 2048

The flag is correctly set (since we have a debugger attached to the process). The next step is to clear it:

(gdb) set $pflag = (*(int *)($pinfo+16))
(gdb) set *(int *)($pinfo+16) = $pflag & ~0x800

Let’s print the value one more time to verify that it’s properly cleared:

(gdb) print (*(int *)($pinfo+16) & 0x800)
$6 = 0

Now that the flag is cleared we can continue executing the process:

(gdb) continue
Continuing.
.
Breakpoint 1, 0x35b60672 in sysctl ()
(gdb)

The breakpoint is hit again because the application is running the sysctl check inside a while loop. We need to have GDB execute all the commands we used above every time a breakpoint is triggered. To accomplish that we can use the “commands” gdb command: GDB commands for the sysctl breakpoint:

commands 1
silent
set $pinfo=$r2
continue
end

GDB commands for the breakpoint after sysctl has returned:

commands 2
silent
set $pflag = (*(int *)($pinfo+16))
set *(int *)($pinfo+16) = $pflag & ~0x800
set $pinfo=-1
continue
end

On the above commands make sure to replace the numbers 1 and 2 with the correct breakpoint numbers. GDB prints the breakpoint number every time a breakpoint is set. We can also use the “info breakpoints” commands to display all the breakpoints.

Now we can resume execution.

(gdb) cont
Continuing.
............

The application runs without detecting the debugger :)


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


SYSCTL(3)                BSD Library Functions Manual                SYSCTL(3)

NAME
     sysctl
, sysctlbyname, sysctlnametomib -- get or set system information

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <sys/types.h>
     #include <sys/sysctl.h>


     int
     sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp, size_t newlen);

     int
     sysctlbyname(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen);

     int
     sysctlnametomib(const char *name, int *mibp, size_t *sizep);

DESCRIPTION
     The sysctl() function retrieves system information and allows processes with appropriate privileges to
     set system information.  The information available from sysctl() consists of integers, strings, and
     tables.  Information may be retrieved and set from the command interface using the sysctl(8) utility.

     Unless explicitly noted below, sysctl() returns a consistent snapshot of the data requested.  Consis-tency Consistency
     tency is obtained by locking the destination buffer into memory so that the data may be copied out
     without blocking.  Calls to sysctl() are serialized to avoid deadlock.

     The state is described using a ``Management Information Base'' (MIB) style name, listed in name, which
     is a namelen length array of integers.

     The sysctlbyname() function accepts an ASCII representation of the name and internally looks up the
     integer name vector.  Apart from that, it behaves the same as the standard sysctl() function.  For a
     list of ASCII representations of commonly used sysctl names, please see sysctl(1).

     The information is copied into the buffer specified by oldp.  The size of the buffer is given by the
     location specified by oldlenp before the call, and that location gives the amount of data copied after
     a successful call and after a call that returns with the error code ENOMEM.  If the amount of data
     available is greater than the size of the buffer supplied, the call supplies as much data as fits in
     the buffer provided and returns with the error code ENOMEM.  If the old value is not desired, oldp and
     oldlenp should be set to NULL.

     The size of the available data can be determined by calling sysctl() with the NULL argument for oldp.
     The size of the available data will be returned in the location pointed to by oldlenp.  For some opera-tions, operations,
     tions, the amount of space may change often.  For these operations, the system attempts to round up so
     that the returned size is large enough for a call to return the data shortly thereafter.

     To set a new value, newp is set to point to a buffer of length newlen from which the requested value is
     to be taken.  If a new value is not to be set, newp should be set to NULL and newlen set to 0.

     The sysctlnametomib() function accepts an ASCII representation of the name, looks up the integer name
     vector, and returns the numeric representation in the mib array pointed to by mibp.  The number of ele-ments elements
     ments in the mib array is given by the location specified by sizep before the call, and that location
     gives the number of entries copied after a successful call.  The resulting mib and size may be used in
     subsequent sysctl() calls to get the data associated with the requested ASCII name.  This interface is
     intended for use by applications that want to repeatedly request the same variable (the sysctl() func-tion function
     tion runs in about a third the time as the same request made via the sysctlbyname() function).  The
     sysctlnametomib() function is also useful for fetching mib prefixes and then adding a final component.
     For example, to fetch process information for processes with pid's less than 100:

           int i, mib[4];
           size_t len;
           struct kinfo_proc kp;

           /* Fill out the first three components of the mib */
           len = 4;
           sysctlnametomib("kern.proc.pid", mib, &len);

           /* Fetch and print entries for pid's < 100 */
           for (i = 0; i < 100; i++) {
                   mib[3] = i;
                   len = sizeof(kp);
                   if (sysctl(mib, 4, &kp, &len, NULL, 0) == -1)
                           perror("sysctl");
                   else if (len > 0)
                           printkproc(&kp);
           }

     Note:  Implementation of printkproc() -- to print whatever data deemed necessary from the large
     kinfo_proc structure ( <sys/sysctl.h> ) -- is left as an exercise for the reader.

     The top level names are defined with a CTL_ prefix in <sys/sysctl.h>, and are as follows.  The next and
     subsequent levels down are found in the include files listed here, and described in separate sections
     below.

           Name           Next level names    Description
           CTL_DEBUG      sys/sysctl.h        Debugging
           CTL_VFS        sys/mount.h         File system
           CTL_HW         sys/sysctl.h        Generic CPU, I/O
           CTL_KERN       sys/sysctl.h        High kernel limits
           CTL_MACHDEP    sys/sysctl.h        Machine dependent
           CTL_NET        sys/socket.h        Networking
           CTL_USER       sys/sysctl.h        User-level
           CTL_VM         sys/resources.h     Virtual memory (struct loadavg)
           CTL_VM         sys/vmmeter.h       Virtual memory (struct vmtotal)

     For example, the following retrieves the maximum number of processes allowed in the system:

           int mib[2], maxproc;
           size_t len;

           mib[0] = CTL_KERN;
           mib[1] = KERN_MAXPROC;
           len = sizeof(maxproc);
           sysctl(mib, 2, &maxproc, &len, NULL, 0);

     To retrieve the standard search path for the system utilities:

           int mib[2];
           size_t len;
           char *p;

           mib[0] = CTL_USER;
           mib[1] = USER_CS_PATH;
           sysctl(mib, 2, NULL, &len, NULL, 0);
           p = malloc(len);
           sysctl(mib, 2, p, &len, NULL, 0);

   CTL_DEBUG
     The debugging variables vary from system to system.  A debugging variable may be added or deleted with-out without
     out need to recompile sysctl() to know about it.  Each time it runs, sysctl() gets the list of debug-ging debugging
     ging variables from the kernel and displays their current values.  The system defines twenty (struct
     ctldebug
) variables named debug_ through debug19.  They are declared as separate variables so that they
     can be individually initialized at the location of their associated variable.  The loader prevents mul-tiple multiple
     tiple use of the same variable by issuing errors if a variable is initialized in more than one place.
     For example, to export the variable dospecialcheck as a debugging variable, the following declaration
     would be used:

           int dospecialcheck = 1;
           struct ctldebug debug5 = { "dospecialcheck", &dospecialcheck };

   CTL_VFS
     A distinguished second level name, VFS_GENERIC, is used to get general information about all file sys-tems. systems.
     tems.  One of its third level identifiers is VFS_MAXTYPENUM that gives the highest valid file system
     type number.  Its other third level identifier is VFS_CONF that returns configuration information about
     the file system type given as a fourth level identifier (see getvfsbyname(3) as an example of its use).
     The remaining second level identifiers are the file system type number returned by a statfs(2) call or
     from VFS_CONF.  The third level identifiers available for each file system are given in the header file
     that defines the mount argument structure for that file system.

   CTL_HW
     The string and integer information available for the CTL_HW level is detailed below.  The changeable
     column shows whether a process with appropriate privilege may change the value.

           Second level name          Type          Changeable
           HW_MACHINE                 string        no
           HW_MODEL                   string        no
           HW_NCPU                    integer       no (DEPRECATED)
           HW_BYTEORDER               integer       no
           HW_PHYSMEM                 integer       no
           HW_MEMSIZE                 integer       no
           HW_USERMEM                 integer       no
           HW_PAGESIZE                integer       no
           HW_FLOATINGPOINT           integer       no
           HW_MACHINE_ARCH            string        no

     HW_MACHINE
             The machine class.

     HW_MODEL
             The machine model

     HW_NCPU (DEPRECATED)
             The number of cpus.  It is recommended that you use "hw.physicalcpu" "hw.physicalcpu_max"
             "hw.logicalcpu" or "hw.logicalcpu_max" instead.

     hw.physicalcpu
             The number of physical processors available in the current power management mode.

     hw.physicalcpu_max
             The maximum number of physical processors that could be available this boot.

     hw.logicalcpu
             The number of logical processors available in the current power management mode.

     hw.logicalcpu_max
             The maximum number of logical processors that could be available this boot.

     HW_BYTEORDER
             The byteorder (4,321, or 1,234).

     HW_PHYSMEM
             The bytes of physical memory represented by a 32-bit integer (for backward compatibility). Use
             HW_MEMSIZE instead.

     HW_MEMSIZE
             The bytes of physical memory represented by a 64-bit integer.

     HW_USERMEM
             The bytes of non-kernel memory.

     HW_PAGESIZE
             The software page size.

     HW_FLOATINGPOINT
             Nonzero if the floating point support is in hardware.

     HW_MACHINE_ARCH
             The machine dependent architecture type.

   CTL_KERN
     The string and integer information available for the CTL_KERN level is detailed below.  The changeable
     column shows whether a process with appropriate privilege may change the value.  The types of data cur-rently currently
     rently available are process information, system vnodes, the open file entries, routing table entries,
     virtual memory statistics, load average history, and clock rate information.

           Second level name          Type                   Changeable
           KERN_ARGMAX                integer                no
           KERN_BOOTFILE              string                 yes
           KERN_BOOTTIME              struct timeval         no
           KERN_CLOCKRATE             struct clockinfo       no
           KERN_FILE                  struct file            no
           KERN_HOSTID                integer                yes
           KERN_HOSTNAME              string                 yes
           KERN_JOB_CONTROL           integer                no
           KERN_MAXFILES              integer                yes
           KERN_MAXFILESPERPROC       integer                yes
           KERN_MAXPROC               integer                no
           KERN_MAXPROCPERUID         integer                yes
           KERN_MAXVNODES             integer                yes
           KERN_NGROUPS               integer                no
           KERN_NISDOMAINNAME         string                 yes
           KERN_OSRELDATE             integer                no
           KERN_OSRELEASE             string                 no
           KERN_OSREV                 integer                no
           KERN_OSTYPE                string                 no
           KERN_POSIX1                integer                no
           KERN_PROC                  struct kinfo_proc      no
           KERN_PROF                  node                   not applicable
           KERN_QUANTUM               integer                yes
           KERN_SAVED_IDS             integer                no
           KERN_SECURELVL             integer                raise only
           KERN_UPDATEINTERVAL        integer                no
           KERN_VERSION               string                 no
           KERN_VNODE                 struct vnode           no

     KERN_ARGMAX
             The maximum bytes of argument to execve(2).

     KERN_BOOTFILE
             The full pathname of the file from which the kernel was loaded.

     KERN_BOOTTIME
             A struct timeval structure is returned.  This structure contains the time that the system was
             booted.

     KERN_CLOCKRATE
             A struct clockinfo structure is returned.  This structure contains the clock, statistics clock
             and profiling clock frequencies, the number of micro-seconds per hz tick and the skew rate.

     KERN_FILE
             Return the entire file table.  The returned data consists of a single struct filehead followed
             by an array of struct file, whose size depends on the current number of such objects in the
             system.

     KERN_HOSTID
             Get or set the host id.

     KERN_HOSTNAME
             Get or set the hostname.

     KERN_JOB_CONTROL
             Return 1 if job control is available on this system, otherwise 0.

     KERN_MAXFILES
             The maximum number of files that may be open in the system.

     KERN_MAXFILESPERPROC
             The maximum number of files that may be open for a single process.  This limit only applies to
             processes with an effective uid of nonzero at the time of the open request.  Files that have
             already been opened are not affected if the limit or the effective uid is changed.

     KERN_MAXPROC
             The maximum number of concurrent processes the system will allow.

     KERN_MAXPROCPERUID
             The maximum number of concurrent processes the system will allow for a single effective uid.
             This limit only applies to processes with an effective uid of nonzero at the time of a fork
             request.  Processes that have already been started are not affected if the limit is changed.

     KERN_MAXVNODES
             The maximum number of vnodes available on the system.

     KERN_NGROUPS
             The maximum number of supplemental groups.

     KERN_NISDOMAINNAME
             The name of the current YP/NIS domain.

     KERN_OSRELDATE
             The kernel release version in the format MmmRxx, where M is the major version, mm is the two
             digit minor version, R is 0 if release branch, otherwise 1, and xx is updated when the avail-able available
             able APIs change.

             The userland release version is available from <osreldate.h>; parse this file if you need to
             get the release version of the currently installed userland.

     KERN_OSRELEASE
             The system release string.

     KERN_OSREV
             The system revision string.

     KERN_OSTYPE
             The system type string.

     KERN_POSIX1
             The version of IEEE Std 1003.1 (``POSIX.1'') with which the system attempts to comply.

     KERN_PROC
             Return the entire process table, or a subset of it.  An array of struct kinfo_proc structures
             is returned, whose size depends on the current number of such objects in the system.  The third
             and fourth level names are as follows:

                   Third level name          Fourth level is:
                   KERN_PROC_ALL             None
                   KERN_PROC_PID             A process ID
                   KERN_PROC_PGRP            A process group
                   KERN_PROC_TTY             A tty device
                   KERN_PROC_UID             A user ID
                   KERN_PROC_RUID            A real user ID

     KERN_PROF
             Return profiling information about the kernel.  If the kernel is not compiled for profiling,
             attempts to retrieve any of the KERN_PROF values will fail with ENOENT.  The third level names
             for the string and integer profiling information is detailed below.  The changeable column
             shows whether a process with appropriate privilege may change the value.

                   Third level name      Type                   Changeable
                   GPROF_STATE           integer                yes
                   GPROF_COUNT           u_short[]              yes
                   GPROF_FROMS           u_short[]              yes
                   GPROF_TOS             struct tostruct        yes
                   GPROF_GMONPARAM       struct gmonparam       no

             The variables are as follows:

             GPROF_STATE
                     Returns GMON_PROF_ON or GMON_PROF_OFF to show that profiling is running or stopped.

             GPROF_COUNT
                     Array of statistical program counter counts.

             GPROF_FROMS
                     Array indexed by program counter of call-from points.

             GPROF_TOS
                     Array of struct tostruct describing destination of calls and their counts.

             GPROF_GMONPARAM
                     Structure giving the sizes of the above arrays.

     KERN_QUANTUM
             The maximum period of time, in microseconds, for which a process is allowed to run without
             being preempted if other processes are in the run queue.

     KERN_SAVED_IDS
             Returns 1 if saved set-group and saved set-user ID is available.

     KERN_SECURELVL
             The system security level.  This level may be raised by processes with appropriate privilege.
             It may not be lowered.

     KERN_VERSION
             The system version string.

     KERN_VNODE
             Return the entire vnode table.  Note, the vnode table is not necessarily a consistent snapshot
             of the system.  The returned data consists of an array whose size depends on the current number
             of such objects in the system.  Each element of the array contains the kernel address of a
             vnode struct vnode * followed by the vnode itself struct vnode.

   CTL_MACHDEP
     The set of variables defined is architecture dependent.  The following variables are defined for the
     i386 architecture.

           Second level name    Type                  Changeable
           CPU_CONSDEV          dev_t                 no
           CPU_ADJKERNTZ        int                   yes
           CPU_DISRTCSET        int                   yes
           CPU_BOOTINFO         struct bootinfo       no
           CPU_WALLCLOCK        int                   yes

   CTL_NET
     The string and integer information available for the CTL_NET level is detailed below.  The changeable
     column shows whether a process with appropriate privilege may change the value.

           Second level name          Type                   Changeable
           PF_ROUTE                   routing messages       no
           PF_INET                    IPv4 values            yes
           PF_INET6                   IPv6 values            yes

     PF_ROUTE
             Return the entire routing table or a subset of it.  The data is returned as a sequence of rout-ing routing
             ing messages (see route(4) for the header file, format and meaning).  The length of each mes-sage message
             sage is contained in the message header.

             The third level name is a protocol number, which is currently always 0.  The fourth level name
             is an address family, which may be set to 0 to select all address families.  The fifth and
             sixth level names are as follows:

                   Fifth level name          Sixth level is:
                   NET_RT_FLAGS              rtflags
                   NET_RT_DUMP               None
                   NET_RT_IFLIST             0 or if_index
                   NET_RT_IFMALIST           0 or if_index

             The NET_RT_IFMALIST name returns information about multicast group memberships on all inter-faces interfaces
             faces if 0 is specified, or for the interface specified by if_index.

     PF_INET
             Get or set various global information about the IPv4 (Internet Protocol version 4).  The third
             level name is the protocol.  The fourth level name is the variable name.  The currently defined
             protocols and names are:

             Protocol      Variable      Type      Changeable
             icmp          bmcastecho    integer   yes
             icmp          maskrepl      integer   yes
             ip            forwarding    integer   yes
             ip            redirect      integer   yes
             ip            ttl           integer   yes
             udp           checksum      integer   yes

             The variables are as follows:

             icmp.bmcastecho
                     Returns 1 if an ICMP echo request to a broadcast or multicast address is to be
                     answered.

             icmp.maskrepl
                     Returns 1 if ICMP network mask requests are to be answered.

             ip.forwarding
                     Returns 1 when IP forwarding is enabled for the host, meaning that the host is acting
                     as a router.

             ip.redirect
                     Returns 1 when ICMP redirects may be sent by the host.  This option is ignored unless
                     the host is routing IP packets, and should normally be enabled on all systems.

             ip.ttl  The maximum time-to-live (hop count) value for an IP packet sourced by the system.
                     This value applies to normal transport protocols, not to ICMP.

             udp.checksum
                     Returns 1 when UDP checksums are being computed and checked.  Disabling UDP checksums
                     is strongly discouraged.

                     For variables net.inet.*.ipsec, please refer to ipsec(4).

     PF_INET6
             Get or set various global information about the IPv6 (Internet Protocol version 6).  The third
             level name is the protocol.  The fourth level name is the variable name.

             For variables net.inet6.* please refer to inet6(4).  For variables net.inet6.*.ipsec6, please
             refer to ipsec(4).

   CTL_USER
     The string and integer information available for the CTL_USER level is detailed below.  The changeable
     column shows whether a process with appropriate privilege may change the value.

           Second level name           Type          Changeable
           USER_BC_BASE_MAX            integer       no
           USER_BC_DIM_MAX             integer       no
           USER_BC_SCALE_MAX           integer       no
           USER_BC_STRING_MAX          integer       no
           USER_COLL_WEIGHTS_MAX       integer       no
           USER_CS_PATH                string        no
           USER_EXPR_NEST_MAX          integer       no
           USER_LINE_MAX               integer       no
           USER_POSIX2_CHAR_TERM       integer       no
           USER_POSIX2_C_BIND          integer       no
           USER_POSIX2_C_DEV           integer       no
           USER_POSIX2_FORT_DEV        integer       no
           USER_POSIX2_FORT_RUN        integer       no
           USER_POSIX2_LOCALEDEF       integer       no
           USER_POSIX2_SW_DEV          integer       no
           USER_POSIX2_UPE             integer       no
           USER_POSIX2_VERSION         integer       no
           USER_RE_DUP_MAX             integer       no
           USER_STREAM_MAX             integer       no
           USER_TZNAME_MAX             integer       no

     USER_BC_BASE_MAX
             The maximum ibase/obase values in the bc(1) utility.

     USER_BC_DIM_MAX
             The maximum array size in the bc(1) utility.

     USER_BC_SCALE_MAX
             The maximum scale value in the bc(1) utility.

     USER_BC_STRING_MAX
             The maximum string length in the bc(1) utility.

     USER_COLL_WEIGHTS_MAX
             The maximum number of weights that can be assigned to any entry of the LC_COLLATE order keyword
             in the locale definition file.

     USER_CS_PATH
             Return a value for the PATH environment variable that finds all the standard utilities.

     USER_EXPR_NEST_MAX
             The maximum number of expressions that can be nested within parenthesis by the expr(1) utility.

     USER_LINE_MAX
             The maximum length in bytes of a text-processing utility's input line.

     USER_POSIX2_CHAR_TERM
             Return 1 if the system supports at least one terminal type capable of all operations described
             in IEEE Std 1003.2 (``POSIX.2''), otherwise 0.

     USER_POSIX2_C_BIND
             Return 1 if the system's C-language development facilities support the C-Language Bindings
             Option, otherwise 0.

     USER_POSIX2_C_DEV
             Return 1 if the system supports the C-Language Development Utilities Option, otherwise 0.

     USER_POSIX2_FORT_DEV
             Return 1 if the system supports the FORTRAN Development Utilities Option, otherwise 0.

     USER_POSIX2_FORT_RUN
             Return 1 if the system supports the FORTRAN Runtime Utilities Option, otherwise 0.

     USER_POSIX2_LOCALEDEF
             Return 1 if the system supports the creation of locales, otherwise 0.

     USER_POSIX2_SW_DEV
             Return 1 if the system supports the Software Development Utilities Option, otherwise 0.

     USER_POSIX2_UPE
             Return 1 if the system supports the User Portability Utilities Option, otherwise 0.

     USER_POSIX2_VERSION
             The version of IEEE Std 1003.2 (``POSIX.2'') with which the system attempts to comply.

     USER_RE_DUP_MAX
             The maximum number of repeated occurrences of a regular expression permitted when using inter-val interval
             val notation.

     USER_STREAM_MAX
             The minimum maximum number of streams that a process may have open at any one time.

     USER_TZNAME_MAX
             The minimum maximum number of types supported for the name of a timezone.

   CTL_VM
     The string and integer information available for the CTL_VM level is detailed below.  The changeable
     column shows whether a process with appropriate privilege may change the value.

           Second level name          Type                 Changeable
           VM_LOADAVG                 struct loadavg       no
           VM_PAGEOUT_ALGORITHM       integer              yes
           VM_SWAPPING_ENABLED        integer              maybe
           VM_V_CACHE_MAX             integer              yes
           VM_V_CACHE_MIN             integer              yes
           VM_V_FREE_MIN              integer              yes
           VM_V_FREE_RESERVED         integer              yes
           VM_V_FREE_TARGET           integer              yes
           VM_V_INACTIVE_TARGET       integer              yes
           VM_V_PAGEOUT_FREE_MIN      integer              yes

     VM_LOADAVG
             Return the load average history.  The returned data consists of a struct loadavg.

     VM_PAGEOUT_ALGORITHM
             0 if the statistics-based page management algorithm is in use or 1 if the near-LRU algorithm is
             in use.

     VM_SWAPPING_ENABLED
             1 if process swapping is enabled or 0 if disabled.  This variable is permanently set to 0 if
             the kernel was built with swapping disabled.

     VM_V_CACHE_MAX
             Maximum desired size of the cache queue.

     VM_V_CACHE_MIN
             Minimum desired size of the cache queue.  If the cache queue size falls very far below this
             value, the pageout daemon is awakened.

     VM_V_FREE_MIN
             Minimum amount of memory (cache memory plus free memory) required to be available before a
             process waiting on memory will be awakened.

     VM_V_FREE_RESERVED
             Processes will awaken the pageout daemon and wait for memory if the number of free and cached
             pages drops below this value.

     VM_V_FREE_TARGET
             The total amount of free memory (including cache memory) that the pageout daemon tries to main-tain. maintain.
             tain.

     VM_V_INACTIVE_TARGET
             The desired number of inactive pages that the pageout daemon should achieve when it runs.
             Inactive pages can be quickly inserted into process address space when needed.

     VM_V_PAGEOUT_FREE_MIN
             If the amount of free and cache memory falls below this value, the pageout daemon will enter
             "memory conserving mode" to avoid deadlock.

RETURN VALUES
     Upon successful completion, the value 0 is returned; otherwise the value -1 is returned and the global
     variable errno is set to indicate the error.

ERRORS
     The following errors may be reported:

     [EFAULT]           The buffer name, oldp, newp, or length pointer oldlenp contains an invalid address.

     [EINVAL]           The name array is less than two or greater than CTL_MAXNAME.

     [EINVAL]           A non-null newp is given and its specified length in newlen is too large or too
                        small.

     [ENOMEM]           The length pointed to by oldlenp is too short to hold the requested value.

     [ENOMEM]           The smaller of either the length pointed to by oldlenp or the estimated size of the
                        returned data exceeds the system limit on locked memory.

     [ENOMEM]           Locking the buffer oldp, or a portion of the buffer if the estimated size of the
                        data to be returned is smaller, would cause the process to exceed its per-process
                        locked memory limit.

     [ENOTDIR]          The name array specifies an intermediate rather than terminal name.

     [EISDIR]           The name array specifies a terminal name, but the actual name is not terminal.

     [ENOENT]           The name array specifies a value that is unknown.

     [EPERM]            An attempt is made to set a read-only value.

     [EPERM]            A process without appropriate privilege attempts to set a value.

FILES
     <sys/sysctl.h>        definitions for top level identifiers, second level kernel and hardware identi-fiers, identifiers,
                           fiers, and user level identifiers
     <sys/socket.h>        definitions for second level network identifiers
     <sys/gmon.h>          definitions for third level profiling identifiers
     <mach/vm_param.h>     definitions for second level virtual memory identifiers
     <netinet/in.h>        definitions for third level IPv4/IPv6 identifiers and fourth level IPv4/v6 iden-tifiers identifiers
                           tifiers
     <netinet/icmp_var.h>  definitions for fourth level ICMP identifiers
     <netinet/icmp6.h>     definitions for fourth level ICMPv6 identifiers
     <netinet/udp_var.h>   definitions for fourth level UDP identifiers

SEE ALSO
     sysctl(1), sysconf(3), sysctl(8)

HISTORY
     The sysctl() function first appeared in 4.4BSD.

BSD                            October 21, 2008                            BSD

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值