[Question]
  [
## Challenge:
In the programming language of your choice, shut down the machine that your code was executed on.
# Rules
* No shutting down by resource exhaustion (e.g.: forkbomb to force shutdown)
* You are allowed to write code that only works in a specific environment/OS, if you wish.
* Standard loopholes are forbidden
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), thus the lowest amount of bytes wins!
  
[Answer]
# [Assembly (x86/x64, Linux, as)](https://sourceware.org/binutils/docs/as/index.html), ~~22~~ ~~21~~ 19 bytes
```
mov  $0x58,       %al  # 2 bytes: b0 58
mov  $0xfee1dead, %ebx # 5 bytes: bb ad de e1 fe
mov  $0x28121969, %ecx # 5 bytes: b9 69 19 12 28
mov  $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
int  $0x80             # 2 bytes: cd 80
```
Must be run as root.
**This is equivalent to pressing the power button and not a safe way to power off your PC.** Make sure you close all open applications and execute `sync` to flush all file system buffers before executing this program, to at least minimize the risk of file corruption.
### Test run
```
$ as -o poweroff.o poweroff.s
$ ld -o poweroff   poweroff.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400078
$ sudo sh -c 'sync && ./poweroff'
root's password:
```
Followed by darkness.
### How it works
`int $0x80` invokes a software interrupt. It works on both x86 and x64, but has been deprecated for over a decade now and should not be used in production code. x64 code should use `syscall` instead. x86 should use `sysenter`, but it is too cumbersome for code golf.
The resulting action from the syscall depends on registers EAX - EDX, ESI, and EDI. The [Linux Syscall Reference](http://syscalls.kernelgrok.com/) shows all syscalls that are available via `int $0x80`.
When EAX holds **0x58 (88)**, *[reboot](http://man7.org/linux/man-pages/man2/reboot.2.html)* is called, which can also be used to power off, put to sleep, or hibernate the computer, as well as switching kernels and disabling or enabling the **Ctrl - Alt - Del** key combo.
At the start of the program – and by compiling with `as` or `gcc -nostdlib`, we can make sure that we're actually at the start of the program – most registers are set to **0**. This includes EAX, so we can use `mov $0x58, %al` to set the lower 8 bits of EAX to **0x58**, thus setting EAX itself to **0x58**. This saves two bytes over manually zeroing the register with `xor %eax, %eax` and one more over the straighforward `mov $0x58, %eax` which encodes **0x58** in 32 bits.
The first two arguments to *reboot* are magic numbers, presumably to prevent accidental reboots, and are read from registers EBX and ECX. Unless these numbers are equal to certain constants, *reboot* refuses to perform any action.
* The first magic number must equal **0xfee1dead** (*feel dead*), probably referring to the power off / death of the PC.
* The second magic number can be equal to four different constants, although the latter three did not work in ancient versions of Linux. All of them seem to refer to the subsequent power on / birth of the PC.
	+ **0x28121969** represents Linus Torvalds's birthday (December 28, 1969).
	+ **0x05121996** represents Patricia Torvalds's birthday (December 5, 1996).
	+ **0x16041998** represents Daniela Torvalds's birthday (April 16, 1998).
	+ **0x20112000** represents Celeste Torvalds's birthday (November 20, 2000).Patricia, Daniela, and Celeste Torvalds are Linus Torvalds's three daughters.
* The EDX register selects the type of "reboot" we want. **0x4321fedc** is *RB\_POWER\_OFF*, shutting the PC down and powering it off.
* Finally, the value of the ESI register is ignored for *RB\_POWER\_OFF*; the value of the EDI register is ignored entirely by *reboot*.
### Alternate version, x64-only, 19 bytes
On x64, we can use a proper syscall for the same byte count.
```
mov     $0xa9,       %al  # 2 bytes: b0 a9
mov     $0xfee1dead, %edi # 5 bytes: bf ad de e1 fe
mov     $0x28121969, %esi # 5 bytes: be 69 19 12 28
mov     $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
syscall                   # 2 bytes: 0f 05
```
The only differences lie in the instruction (`syscall` vs `int $0x80`), the value of *\_\_NR\_REBOOT* (**0xa9** vs **0x58**), and the involved registers.
[Answer]
# PowerShell, 13 bytes
```
Stop-Computer
```
Pretty self-explanatory? Doesn't work on PowerShell core, so it won't work on PowerShell for Linux/MacOS (already tried it on TIO :-D ).
## Bonus Garbage Submission, 12 bytes
```
gcm s*r|iex
```
In my testing, this works on Windows 2003 with PowerShell 2.0. It won't work on most of the newer versions, and it may not work depending on which modules are installed. It's quite terrible!
This searches the list of commands for any with the pattern `s*r` and then runs all of them! To be clear, **this is dangerous, don't do this!**
The trick of course, is getting a list of commands that don't have any mandatory parameters, otherwise PowerShell will prompt for a value.
On my 2003 machine, the 3 commands it returns are:
> 
> 
> ```
> CommandType     Name                                                Definition                                         
> -----------     ----                                                ----------                                         
> Application     scrnsave.scr                                        C:\WINDOWS\system32\scrnsave.scr                   
> Application     ssmarque.scr                                        C:\WINDOWS\system32\ssmarque.scr                   
> Cmdlet          Stop-Computer                                       Stop-Computer [[-ComputerName] <String[]>] [[-Cr...
> 
> ```
> 
> 
Yes, it does launch the marquee screensaver, but no, it does not wait for it to complete before launching `Stop-Computer`.
This approach can work on newer machines, again depending on which modules are installed, but the best I could do on Windows 2012 and 2016 was **14 bytes**:
```
gcm sto*er|iex
```
(and yeah, sure, the winbatch submission will work in PowerShell and it's shorter, but.. that's no fun)
[Answer]
## Batch, 10 bytes
On windows, this would suffice
```
shutdown/s
```
This will set up a shutdown in one minute.
Alternatively, as @flashbang points out:
```
shutdown/p
```
This shuts down the computer immediately.
[Answer]
## x86 machine code, Lenovo Z510, DOS COM or Bootloader, 7 bytes
```
BITS 16
mov ax, (1 << 13) | (7 << 10)
mov dx, 1804h
out dx, ax
```
Assembled into `B8 00 3C BA 04 18 EF`
I'm exploiting "*You are allowed to write code that only works in a specific environment/OS, if you wish*" to the ultimate level: this will only work on Lenovo Z5101.
This writes `SLP_TYPa << 10 | SLP_EN` to the `PM1a_CNT` ACPI register, I dumped this values from the ACPI tables [months ago for an answer about shutdown](https://stackoverflow.com/a/40002262/5801661) (where I give a bit of context to the code above). 
This can be run either under DOS as a COM (just write the binary data into a file and change extension to "com") or as a bootloader.  
For the latter write the standard signature and [beware of the issues with modern firmware](https://stackoverflow.com/a/39248323/5801661).
---
1 Not strictly true, any system that happens to have the same ACPI configuration will also shutdown.
[Answer]
# [GRUB shell](https://www.gnu.org/software/grub/manual/grub.html), 4 bytes
**Golfed**
```
halt
```
> 
> Command: halt --no-apm
> 
> 
> The command halts the computer. If the --no-apm option is specified, no APM BIOS call is performed. Otherwise, the computer is shut down using APM.
> 
> 
> 
**Bonus**
Here is a proof that GRUB shell is indeed Tur**n**ing-complete (see comments):
[![enter image description here](https://i.stack.imgur.com/P4rfO.gif)](https://i.stack.imgur.com/P4rfO.gif)
[Answer]
# 65C02 machine code, 1 byte
STP instruction (0xDB):
STP stops the clock input of the 65C02, effectively shutting down the 65C02 until a hardware reset occurs (i.e. the RES pin goes low). This puts the 65C02 into a low power state. This is useful for applications (circuits) that require low power consumption, but STP is rarely seen otherwise.
(Source: <http://www.6502.org/tutorials/65c02opcodes.html>)
xxd dump:
```
00000000: db                                       .
```
[Answer]
# Matlab, 21 Bytes
```
system('shutdown -s')
```
~~I haven't tried this (closing all programs to do a restart in the middle of the day isn't really tempting), but it should work.~~. This works...
I'll add a short explanation later, my laptop is currently off.
[Answer]
# MATLAB, 11 bytes
```
!shutdown/p
```
Somewhat similar to [Stewie Griffin's approach](https://codegolf.stackexchange.com/a/107878/32352). However, MATLAB has ***way*** shorter ways of invoking system commands; in this case, `!` is used. Windows does not need `.exe` for command names, so that's left out as well. The `/` option is still supported (I'm running Windows 10), and negates the need for the space. Alternatives are:
```
system shutdown/p % 17 bytes; uses so-called 'command' syntax.
dos shutdown/p    % 14 bytes; the 'dos' command can be used just as well.
```
[Answer]
# SmileBASIC, ~~14~~ ~~11~~ 6 bytes
```
OPTION
```
Triggers a crash causing the 3DS to restart.
I hope this counts.
Works in the most recent version.
[Answer]
# Bash, ~~7~~ 6 bytes
```
init 0
```
Assuming that the program is run as root.
[Answer]
# Commodore 64, 11 bytes
```
0 sys64738
```
This is from the BASIC prompt. Or...
### Commodore 64, 6502 assembly, 3 bytes (assembled), 16 bytes (source)
```
*=8000
JMP $FCE2
```
[Answer]
# Python 2, 29 bytes
```
import os;os.system('init 0')
```
Works on Linux systems and needs root privileges.
**For Windows, 33 bytes**
```
import os;os.system('shutdown/p')
```
[Answer]
# Java, 101 98 62 42 bytes
```
()->{Runtime.getRuntime().exec("init 0");}
```
As @Snowman pointed out, the question didn't specify if a full program was needed, so this should still be acceptable.
[Answer]
# AppleScript, 30 bytes
```
tell app "Finder" to shut down
```
Does exactly what it says: tells Finder to shut the computer off.
[Answer]
## TI-Nspire CX CAS, 3 bytes
```
" "+" "
```
*summing two empty strings.*
On an older version of the calculator, this would crash the device and cause it to reboot (there's no way to shutdown a device without reboot apart from physical button combinations).
[Video](https://www.youtube.com/watch?v=QvxFxzDgS2U) by Adriweb
[Answer]
# C++, 51 40 bytes
-11 bytes thanks to [Ingve](https://codegolf.stackexchange.com/users/64901/ingve)!
```
#include<os>
int main(){OS::shutdown();}
```
Only works in [IncludeOS](http://www.includeos.org/) (v0.10.0-rc.1)
Test:
```
$ pwd
/home/simon/IncludeOS/examples/demo_service
$ cat service.cpp
#include<os>
int main(){OS::shutdown();}
$ mkdir build && cd build && cmake .. && make && cd ..
[...]
$ boot build/IncludeOS_example
[...]
================================================================================
================================================================================
 IncludeOS v0.10.0-rc.1-9-g151a2b9
 +--> Running [ IncludeOS minimal example ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$
```
[Answer]
# AutoHotkey, ~~11~~ 10 Bytes
*Saved a byte thanks to [Gurupad Mamadapur](https://codegolf.stackexchange.com/users/47650/gurupad-mamadapur)*
```
Shutdown,9
```
AHK Supports a Shutdown command by default. The `9` is a flag, consisting of `Shutdown=1` + `PowerDown=8`.
[Answer]
# Machine code (x86, boot loader) 18 bytes
```
b8 01 53 33 db cd 15 b8 07 53 bb 01 00 b9 03 00 cd 15
```
Disassembly:
```
mov ax, 0x5301 ; connect to real-mode APM services
xor bx, bx     ; device id 0 - APM BIOS
int 0x15       ; call APM
mov ax, 0x5307 ; set power state
mov bx, 0x0001 ; on all devices
mov cx, 0x0003 ; to Off
int 0x15       ; call APM
```
You can test it in Bochs' debugger with the following commands (after starting simulation, having some disk drive set up):
```
pb 0x7c00
c
setpmem 0x7c00 4 0x335301b8
setpmem 0x7c04 4 0xb815cddb
setpmem 0x7c08 4 0x01bb5307
setpmem 0x7c0c 4 0x0003b900
setpmem 0x7c10 2 0x15cd
c
```
This same machine code will also work as a DOS executable (`*.COM`).
[Answer]
## C#, 79 54 53 bytes
This works on Windows.
**79 bytes**:
```
class _{static void Main(){System.Diagnostics.Process.Start("shutdown","/s");}}
```
**53 bytes**, thanks to TheLethalCoder:
```
_=>System.Diagnostics.Process.Start("shutdown","/s");
```
[Answer]
# AutoIt, 11 bytes
```
Shutdown(1)
```
Shutdown function gets combination of following codes
```
0 = Logoff
1 = Shutdown
2 = Reboot
4 = Force
8 = Power down
16= Force if hung
32= Standby
64= Hibernate
```
To shutdown and power down, for example, the code would be 9 (shutdown + power down = 1 + 8 = 9).
[Answer]
# Windows - NativeAPI, 212 bytes
Ok this is not really the shortest version.
But maybe interesting to some.
This will *not* execute on the Win32 subsystem. However it will run when executed within the context of the native api (like autochk.exe does)
# Code
```
#define WIN32_NO_STATUS
#include <windef.h>
#include <winnt.h>
#include <ntndk.h>
NTSTATUS main() {
RtlAdjustPrivilege(SE_SHUTDOWN_PRIVILEGE,TRUE,FALSE,NULL);
return ZwShutdownSystem(ShutdownPowerOff);
}
```
# Build
To build this either use the WinDDK `build.exe` tool (with an appropriate `source` file for `NMAKE`)
Or use these commands to compile and link:
```
cl /Gd /D_X86_ /showIncludes /I%DDK_INC_PATH% /I%CRT_INC_PATH% /c main.c
link /verbose /nodefaultlib /subsystem:native /machine:X86 /entry:NtProcessStartup@4 C:\WinDDK\7600.16385.1\lib\win7\i386\nt.lib C:\WinDDK\7600.16385.1\lib\win7\i386\ntdllp.lib C:\WinDDK\7600.16385.1\lib\win7\i386\BufferOverflow.lib .\main.obj 
```
Note: This will build an x86 native executable. Change the appropriate bits if you want to build this for a different architecture.
# Test
To test a native executable you have to execute it **before** the win32 subsystem is loaded. One common way to do it is to append the executable in the following registry key:
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute
```
# Warning
If you do this however, you need to have an option to edit the registry hive of the target OS from another OS. Since **you will not be able to boot the target OS anymore!**
I did it on a VM where i could easily revert to a previous snapshot!
[Answer]
# J, 14 bytes
```
2!:0'poweroff'
```
Works on Linux systems. `2!:0` executes the string in `/bin/sh`.
[Answer]
## Groovy, 23 bytes
```
'shutdown /p'.execute()
```
[Answer]
# Most Linux shells, 15 bytes
```
# echo o>/p*/*ger
```
It could be made to be 11 bytes long, if you happen to be in the `/proc` directory:
```
# echo o>*ger
```
This is very straightforward (has no side effects, like unmounting filesystems or killing processes) and rather brutal.
[Answer]
## Android shell, 9 bytes
```
reboot -p
```
[Answer]
## AppleScript, 44 bytes
```
tell application "Finder"
shut down
end tell
```
I don't know how AppleScript syntax works or anything, so if anybody knows how to shorten this, please tell. 
Also, I'm doing this on my phone at school ("hacking"), so I can't test it. 
At 14 fewer bytes (thanks to kindall) you can say
```
tell app "Finder" to shut down
```
[Answer]
# Clojure, ~~40~~ 39 bytes
```
(.exec(Runtime/getRuntime)"shutdown/s")
```
-1 byte by changing the flag from `-s` to `/s`, which allowed me to get rid of the space.
Basically the Java answer.
Testing this was fun. Windows decided to do a firmware update on my Surface the second it shut down. Of course.
```
(defn shutdown []
  (.exec (Runtime/getRuntime) "shutdown -s"))
```
[Answer]
# Node.js, 39 bytes
Linux
```
require('child_process').exec('init 0')
```
[Answer]
## AHK, ~~19~~ 15 bytes
```
Run,Shutdown -s
```
Works on windows only.
[Answer]
## C++, ~~48~~ 47 (Windows) ~~46~~ 45 (Linux) bytes
Removed 1 byte thanks to Snowman
```
#include<cstdlib>
main(){system("shutdown/p");}
```
This should shutdown the system for windows
```
#include<cstdlib>
main(){system("poweroff");}
```
This should shutdown the system for Linux
]