# Will it halt? (Cops)

Your challenge is to make a program that runs forever without halting1, unless it gets a particular input or inputs2. If it receives that input, it must terminate in a finite amount of time3. This is , so the shortest answer that has not been cracked by a robber within one week of posting wins. After the week has passed, please mark your answer as safe and show the halting input (in a > ! spoiler quote). If a robber cracks your submission, please mark it as cracked and show the halting input (in a > ! spoiler quote).

Submissions are preferred be runnable & crackable on TIO. Submissions not runnable or crackable on TIO are allowed, but please include instructions to download / run them.

Please make your input deterministic, and uniform across all runs. See this meta post for details.

Please, don't "implement RSA" or anything mean to the robbers. Use obscure languages and features, not boring encryption and hashing. I can't enforce this with rules, but you can expect torrential downvotes if all you do is sha(input) === "abcd1234".

1Assuming that the computer doesn't get shut down, break, get engulfed by the sun, overheat in the universe's heat death, or hit the TIO timeout of 60s.

2The program must halt on at least one input. As long as it loops forever on one input and halts on another, it works.

3This must be < 60 seconds, so that the code can be tested on TIO.

# Looking for uncracked submissions?

fetch("https://api.stackexchange.com/2.2/questions/135363/answers?order=desc&sort=activity&site=codegolf&filter=!.Fjs-H6J36vlFcdkRGfButLhYEngU&key=kAc8QIHB*IqJDUFcjEF1KA((&pagesize=100").then(x=>x.json()).then(data=>{var res = data.items.filter(i=>!i.body_markdown.toLowerCase().includes("cracked")).map(x=>{const matched = /^ ?##? ?(?:(?:(?:$|<a href ?= ?".*?">)([^$]+)(?:\]|<\/a>)(?:[$$$][a-z0-9/:\.]+[$$$])?)|([^, ]+)).*[^\d](\d+) ?$?(?:(?:byte|block|codel)s?)(?:$(?:$$.+$$)?)? ?(?:$$?(?!no[nt][ -]competing)$$?)?/gim.exec(x.body_markdown);if(!matched){return;}return {link: x.link, lang: matched[1] || matched[2], owner: x.owner}}).filter(Boolean).forEach(ans=>{var tr = document.createElement("tr");var add = (lang, link)=>{var td = document.createElement("td");var a = document.createElement("a");a.innerHTML = lang;a.href = link;td.appendChild(a);tr.appendChild(td);};add(ans.lang, ans.link);add(ans.owner.display_name, ans.owner.link);document.querySelector("tbody").appendChild(tr);});});
<html><body><h1>Uncracked Submissions</h1><table><thead><tr><th>Language</th><th>Author</th></tr></thead><tbody></tbody></table></body></html>

• @LuisMendo assuming infinite memory is fine – programmer5000 Jul 24 '17 at 16:29
• @programmer5000 Thanks for clarifying. You should incorporate all this into the challenge text. Answerers are not expected to read all comments – Luis Mendo Jul 24 '17 at 16:48
• Can we restrict the input to, say, an integer? A robber could pass in some malformed or mistyped input to terminate the program immediately. I'd either have to do lots of careful input validation, or use a language that can catch arbitrary errors. – xnor Jul 24 '17 at 18:37
• @xnor I think you're supposed to have to do the input checking. – Stephen Jul 24 '17 at 18:49
• @StepHen That works if the malformed input is still able to be parsed by the interpreter. If I enter an illegal string, R errors immediately, without even entering the function to crack. I would argue that that doesn't count as actually terminating the function. – JAD Jul 26 '17 at 5:02

# JavaScript (Browser), 62 bytes (cracked)

x=>{while(!x||(!(x[Symbol.toPrimitive]=()=>true))||+x||true);}


Solution should work in modern browsers on all pages. Is possible without .toPrimitive (or similar) trickery (cracked) - is also possible with .toPrimitive (or similar) trickery (cracked) :P

Intended solutions:

W/o .toPrimitive or similar:

let i = document.createElement("iframe");
document.body.appendChild(i);

W/ .toPrimitive

• Cracked. – Veedrac Jul 26 '17 at 23:07
• @Veedrac Nice! Now we just need the solution without .toPrimitive. – Birjolaxew Jul 27 '17 at 6:22
• @PatrickRoberts I'd say that counts ;) – Birjolaxew Jul 27 '17 at 21:56
• Cracked – Patrick Roberts Jul 27 '17 at 22:40

# Befunge 93, 13 bytes, cracked by ovs

13 bytes: if you crack me you will get bad luck forever!!! ~Spooky~

~345**-0/#v_@


Unfortunately this one's pretty crackable.

• Cracked – ovs Jul 28 '17 at 6:34

# JavaScript (ES7), 25 bytes, Cracked

x=>{for(;!(x&&"."**x););}


Intended solution:

"0"

Try it online!

• – Shaggy Jul 27 '17 at 16:38
• @Shaggy yup, there's a couple other (equivalent) solutions – Stephen Jul 27 '17 at 16:45
• Yeah, I also just found that String.prototype works too. – Shaggy Jul 27 '17 at 16:46
• @Shaggy why the flippity flappity does String.prototype == false – Stephen Jul 27 '17 at 16:47
• Because JS is weird?! Array.prototype also works but, strangely, Object.prototype doesn't. – Shaggy Jul 27 '17 at 16:49

# C (gcc), 144 bytes (Cracked)(Cracked 2) (Intended Crack)

This should be an easy one. Compile without optimizations.

#include <stdio.h>
char*a="abcd";char b[256];fun(){char c['\b'];char*d=a;fgets(c,'\f',stdin);snprintf(b,sizeof(c),c,d);}
main(){while(1)fun();}



Try it online!

# Python, 19 bytes (cracked)

while(lambda:1)():0


How to input:

Write any code above this statement, following some simple restrictions against low-hanging fruit:

• The line must be reached, unconditionally. A solution must reach this line even in unlikely scenarios.
• No threads or processes may be spawned,
• The solution must run on Python 2 (CPython and PyPy) and Python 3 (CPython).
• cracked – pppery Jul 30 '17 at 21:23

# Python 2, 143 bytes (cracked)

from sys import*
def l(*_):
while 1:1
t=lambda*_:l;p=lambda*_:_[1][1]=="_"and l()or settrace(t)
def k(f):
setprofile(p)
try:f()
finally:l()


The warmup was handled faster than expected, so let's go straight to the deep end. Pass one argument to k by appending code to this program. That argument may be initialized imperatively.

• Don't modify k or its dependencies before calling it; you must break k from within. Similarly, don't call sys.setprofile or perform other interpreter modifications when initializing the argument.

• No threads or processes may be spawned,

• The solution must run on CPython and PyPy,

• cracked – pppery Jul 31 '17 at 2:41

# JavaScript (Node.js >= 6.0), 708 694 bytes, Cracked

(_=>{let v=s=>eval(s);{let e=require('events').EventEmitter.prototype;e.listeners=new Proxy(e.listeners,{apply(t,c,a){if(a[0]=='exit')return[];return t.apply(c,a)}});e.removeAllListeners=new Proxy(e.removeAllListeners,{apply(t,c,a){if(a[0]=='exit')return c;return t.apply(c,a)}});let w=new WeakSet();Proxy.revocable=new Proxy(Proxy.revocable,{apply(t,c,a){let r=t.apply(c,a);w.add(r.proxy);return r}});Proxy=new Proxy(Proxy,{construct(t,a,n){let p=new t(...a);w.add(p);return p}});let l=_=>{while(1);};process.on('exit',l);return i=>{try{if(!w.has(i)&&i instanceof Function&&typeof i!='function'&&v(String(i))===i&&i()===String(i)){process.removeListener('exit',l)}else{l()}}catch(o){l()}}}})()


Don't let the size deter you. Most of it is to just prevent you from trying to get past my intended solution doing the "obvious" stuff.

I hope this isn't more simple than I thought it was, but I assure you it's possible. I've tested on my computer and also on TIO to make sure it wasn't dependent on a particular version of Node.js or something.

This is a function submission, so assign it to a variable and call it with your intended input.

And maybe I'm not supposed to enforce this, but the input for the intended crack doesn't require any pre-processing, it can just be solved by doing this:

f=[708 bytes...]


### Comment on @hvd's crack

I will reveal one part of the intended solution, since it is no longer relevant, and hvd's approach was much more elegant anyway.

Object.create((class extends Function{toString(){process.kill(0)}}).prototype)


would have been how I would have written that particular crack, since I had not thought of using __proto__ in an object literal, so kudos.

### Edit 1

Sorry, forgot to invoke the IIFE, otherwise any input would have worked :P

### Edit 2

This doesn't change the challenge at all, it just addresses the comment claiming

Halts with error, let not supported without strict mode. If fix t(...a) is unexpected token.

by explicitly defining the accepted range of versions in which these errors don't occur, making the challenge valid.

### Edit 3

By moving the call to process.on('exit',l) from the function call into the IIFE scope, I prevented the stupid input of

process.on=()=>process.exit()


from working. An interesting side-effect of this change is that not calling the function causes the program to hang as well!

However, the intended solution is still the same, and the rest of the changes were only for golfing purposes. Carry on!

(And the timer for marking "safe" has been reset as of this edit because it is major)

• A slightly easier to work with TIO – Birjolaxew Jul 28 '17 at 12:03
• @Birjolaxew Heh, I see you've discovered the basics of my challenge, but the question remains if you can find the answer~ (at least I hope I've narrowed it to one) – Patrick Roberts Jul 28 '17 at 12:33
• @PatrickRoberts I got stuck on implementing [[Call]] without typeof i === "function" (since that's how the specification defines typeof === "function" :P) – Birjolaxew Jul 28 '17 at 12:37
• @Birjolaxew then how do you explain var call = Function.call; console.log(typeof call); call()? I'm not saying it's entirely useful here, but I'm just playing devil's advocate. – Patrick Roberts Jul 28 '17 at 14:05
• @PatrickRoberts It does work, because the IIFE sees the WeakSet function definition even if it appears later in the code at a point where execution hasn't reached yet. – hvd Jul 30 '17 at 21:41

# Python 3, 228 Bytes (Cracked - Fixed)

I was stupid, and this was cracked because I missed a trivial case. Thanks to Jonathan Allan, it's been fixed, and I resubmit it.

Try it here

p=print
try:
n=input()
except:
while 1:p("i")
try:
while sum(map(int,n))<1or not(int(n[17]+n[:17])==2*int(n[:18])and int(n[45]+n[18:45])==3*int(n[18:46])and int(n[87]+n[46:87])==5*int(n[46:88])):p("m")
except:
while 1:p("x")

• TIO is an online execution environment for programs. For example, you might post this link as a way of sharing your answer through the online environment. – Conor O'Brien Jul 24 '17 at 20:48
• Simple crack would be n a string or list of length less than length 17 causing an IndexError (this is assuming n is already limited to a string or list too). – Jonathan Allan Jul 24 '17 at 21:39
• cracked. Almost certainly not the intended crack, but also without any error raised. – Jonathan Allan Jul 24 '17 at 21:59
• @JonathanAllan You're right. I meant to restrict it to only positive values. Is it acceptable to edit it to correct my oversight? – E.D. Jul 24 '17 at 22:46
• Yeah, I think so, I have not cracked the intended and it seems cool to me - how about this modification? It means it'll be a full program, so only strings ever get in (empty or ctrl-x etc for input - prints "i") and no errors can occur in the evaluation (prints "x"). – Jonathan Allan Jul 24 '17 at 22:52

## BASIC, 8 bytes (Cracked)

1input x

Meets the conditions of the OP completely, other than TIO which was a request not a condition.

Try it.

It'll hang forever (machine stability required) and terminate predictably within << a second of any input. Probably not what the OP meant but perfectly fair. Alls fair in love and golf!

• Hey! Don't give away what the input is. Other people are meant to guess it! (Also, apostrophe.) – wizzwizz4 Jul 26 '17 at 15:04
• Heheeeee! Shall we tell them? After all, anyone inspecting it can work it out. – Stilez Jul 26 '17 at 15:09
• Cracked! – NieDzejkob Jul 26 '17 at 15:58

Lua, 107 Bytes, Cracked

I hate how verbose lua is - getting inputs takes up almost half the program.

x=tonumber(io.read())or 2 y=tonumber(io.read())or 2 if y^(x%5)+x*y+y~=x^3-(x-120)*x then while 1 do end end


I tried to account for all trivial solutions - hopefully this works.

• Is this harder than solving an equation? Cracked. – user202729 Jul 29 '17 at 14:19
• Just for fun, here's my attempt at golfing the code :) – tehtmi Aug 6 '17 at 9:51
• @tehtmi Wow! I didn't try hard to golf this one, but I definitely couldn't have done what you did. I'm still on Lua 5.1, can you explain the "..." to me? – Nico A Aug 6 '17 at 18:28
• ... is used for "vararg" functions. E.g. function myprint(category,...)print("My Print ["..category.."]:",...)end. If ... is used at the end of an expression list (arguments or assignment), it is like arg1, arg2, arg3, -- and so on. x,y=... is like x,y=arg1,arg2. When running from the command line, the outer-level of the script is implicitly a function and the command line arguments are passed to it. E.g. lua my_script.lua arg1 arg2. The arguments are also in a table called arg which also includes the others components of the command line call at arg[0], arg[-1], etc. – tehtmi Aug 6 '17 at 19:27
• @tehtmi Wow, I knew that, but I never thought of taking input from command line... this really helps one of the programs I'm working on. Thank you! – Nico A Aug 7 '17 at 0:52

# Swift 3, 77 bytes (safe)

extension Bool{prefix static func !(b:Bool)->Bool{return true}}
while !true{}


To solve this, put your code before or after this statement.

• keep this statement intact, without modifying its code
• actually let this statement run
• Simply commenting it out, calling fatalError(), etc. before it doesn't count.
• modify the behavior of this statement to prevent it from looping forever
• The solution does not involve crashing the program.

This code is a refinement of my previous (cracked) attempt, here.

The first line of this code exists solely to prevent the exploit found by @Veedrac.
true in while !true is not actually a Bool. It's a boolean literal. Any type that conforms to ExpressibleByBooleanLiteral can be initialized from a boolean literal. Usually, the correct ExpressibleByBooleanLiteral to be instantiated is inferred from the context where it's needed. If, such as in this case, the context does not provide any type information as to the kind of ExpressibleByBooleanLiteral needed, the compiler falls back to choosing BooleanLiteralType as the default.

By default, the value of BooleanLiteralType is Bool. This makes sense. In the absence of contextual type information, true and false are both used to initialize instances of Bool. Interestingly, BooleanLiteralType can be overridden locally. My solution exploits this by creating a ExploitBool type, and sets it to be the preferred type for boolean literals, so the true in while !true is actually an instance of ExploitBool. I then define a prefix ! operator, so that for all instances x of ExploitBool, x returns true as a Bool.


// First, set up the exploitive data type we need:
struct ExploitBool: ExpressibleByBooleanLiteral {
init(booleanLiteral _: Bool) {
// ignore booleanLiteral, we don't care about it
}

// Define the prefix ! as an operator that acts on a ExploitBool,
// and always just returns false (as a regular Bool)
prefix static func !(b: ExploitBool) -> Bool {
return false
}
}

// Then, set it as the preferred type to instantiated from
//boolean literals in the absense of other contextual type information.
typealias BooleanLiteralType = ExploitBool

extension Bool{prefix static func !(b:Bool)->Bool{return true}}
while !true{}


x=>{try{while(typeof x!='string'||!x.match^[()[\\]!+]{4321}$|eval(x)!='☆');}catch(e){for(;;);}}  Try it online! # x86-64, 5 bytes assembled, SAFE halty: verr si jnz$
ret


This is a pretty simple "warm up" I came up with. Shouldn't be difficult at all to crack. Takes input in rsi.

Why did this win.

The solution is simple, at least on my computer. rsi == 32 will cause it to halt. In fact, it has multiple possible inputs that will cause it to halt. verr checks if the segment supplied in %r can be read. IF it can't, the zero flag is set, and the function returns.

• I think a 0 as input would halt this one (line 3 is jump if not zero). I don't have a way to run it and check though. – Draco18s no longer trusts SE Oct 15 '18 at 0:19

# Simplefunge, 1028 bytes, safe

0ooooooooooooooooooooooOOOOOOOOOOOOoo9ooOOoOOoOOoOoOOoOoOoOOOOoOoOoOoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooIOoOoOoOoOOoOOooOOo-ov
ooooOOOOooOOoOOoOOoOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooOOOOOOOOooooooo
ooooOOOOooOOoOOoOOoOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooOOOOOOOOooooooO
ooooOOOOooOOoOOoOOoOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooOOOOOOOOooooooo
ooooOOOOooOOoOOoOOoOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooOOOOOOOOooooooO
ooooOOOOooOOoOOoOOoOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooOOOOOOOOooooooo
ooooOOOOooOOoOOoOOoOOoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo@oooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooOOOOOOOOoooooH


The answer is the tab character

Try it online!

• Um, this halts with no input – Jo King Feb 24 '19 at 23:33
• Oh, okay. Does that count? – MilkyWay90 Feb 24 '19 at 23:40

# JavaScript (Node.js), 26 bytes (Cracked, not intended solution)

x=>{while(x.constructor);}


Try it online!

# JavaScript, cracked

x=>{try{for(;x.x||!x.x;);}catch(e){for(;;);}}


Try it online!

# Java (OpenJDK 8), 517 bytes (safe)

import java.lang.reflect.Constructor;
import java.util.Map;
class M{
public static void main(String[] cm){
try{
Class<?>cl=Class.forName(cm[0]);
Constructor<?>ct=cl.getConstructor();
Map<Integer,Integer>m=(Map)ct.newInstance();
String str="Hello World";
for (int i=0;i<str.length();i++){
char c=str.charAt(i);
int cc=m.getOrDefault(new Integer(c),new Integer(0));
cc++;
m.put(new Integer(c),new Integer(cc));
}
while(m.size()<9);
}catch(Throwable t){
while(true);
}
}
}


Try it online!

Input via the command line arguments.

A little long and verbose, but hey, it's got reflection!

# Golfed a little more, 432 bytes

(Thanks to Stephen!)

import java.lang.reflect.Constructor;import java.util.Map;class M{public static void main(String[]a){try{Class<?>l=Class.forName(a[0]);Constructor<?>t=l.getConstructor();Map<Integer,Integer>m=(Map)t.newInstance();String s="Hello World";for(int i=0;i<s.length();i++){char c=s.charAt(i);int C=m.getOrDefault(new Integer(c),new Integer(0));C++;m.put(new Integer(c),new Integer(C));}while(m.size()<9);}catch(Throwable t){while(true);}}}


Halting input:

java.util.IdentityHashMap

• It seems very long to me for a code-golf. – Toto Sep 13 '17 at 12:34
• Welcome to PPCG! I know this is cops-and-robbers, but you can get 432 bytes by golfing variable names and whitespace: Try it online! – Stephen Sep 13 '17 at 12:58
• @Toto It's indeed not the golfiest thing in the world, but it does use some rather unusual features of Java. – Jonathan S. Sep 13 '17 at 13:04
• @Stephen Thanks a lot! Had to leave the computer for a while and wanted to post the thing before I went. :) (Double comment because I can't mention two people at once) – Jonathan S. Sep 13 '17 at 13:05

# BrainF - Cracked

,[->+>+<<]>>[-<<+>>]<<[->+<]>------------------------------------------------------------------------------------------------[.]


Should be easy to reverse engineer it.

• Cracked – Draco18s no longer trusts SE Dec 19 '18 at 3:29
• What's BrainF? Do you mean brainfuck? – Jo King Dec 19 '18 at 3:48
• Yes I do, but I do not like cursing. – MilkyWay90 Dec 20 '18 at 0:12

## CPython 3.6, 635 634 bytes Cracked

j=input()
__builtins__.__dict__["__import__"]=eval(j)
import random,functools,itertools,zlib
exec("@functools.lru_cache(None)\ndef f():i=input();return(all(x is y for x,y in itertools.zip_longest((x for x in sorted(dir(eval(i[::2])))if'_'not in x),sorted{}))\nand all(x is y for x,y in itertools.zip_longest((x for x in sorted(dir(eval(i[1::2])))if'_'not in x),sorted{}))and 8 and zlib.crc32(bytes(i,'ASCII'))==zlib.crc32(bytes(j,'ASCII')))".format(*eval('('+"(tuple(''.join(random.choice('abcdefghijklmnopqrstuvwxyz')for x in range%s)for x in range%s),),"%(("(random.randint(1,9))",)*2)*2+')')))
try:f()
except:f=bool
while not f():8


Try it online!

It probably works in some other versions too, but I haven't tested it in them. Golfing advice welcome.

Note that triggering an EOFError is cheaty - this program expects streams to remain open!

I also have an ungolfed version, complete with terrible, terrible ASCII art, prettified output and probable cryptographic security.

import_input = input()
__builtins__.__dict__["__import__"] = eval(import_input)

import secrets
import functools
import itertools
import zlib
import base64

code = b"""
GA2
@ >T   )Ec#  6     *  C       WM 2 +0    4.            ^1
+   5  i      T    m   \'     J   ]   7  g                q
e     -+     D V_4W  a ,    :C<  G  E*t
3   GW0P0V/bkg iU>       o    %hb  &  CM_
n      Y 1!SHJIUjh^     iZ    Ol5  %  =n4   Qb   21   Z>A
R    l& j       iSDh  c>j  ;#  @h  E  ?l    B  W h  # u
di-90o @\\O"t6XNM8boo1T   /JHW     c        Y,@  H    N Ok
?pDT:)     (        (        %  F
3<uEZ_BZ"\\hNA)a.1W_9\\)/e%/ROb    2        V     ?5   3q
c5g^O89kP>iuQ3*GZHb>#u0%gcC_6(    i
L                           Es/    V
6                           >qD    m       H              6
,                           D;$J K , :K O U ? I0L(# d = C 9  f$g3<"""

alphabet = "abcdefghijklmnopqrstuvwxyz"
make_keyword = lambda l:"".join(secrets.choice(alphabet) for x in range(l))
exec(zlib.decompress(base64.a85decode(code)[::-1]).decode("ASCII").format(
*eval('('+"(tuple(make_keyword(secrets.randbelow(20)+1)"
"for x in range(secrets.randbelow(20)+1)),),"*2+')')))

try:
f()
except:
f = bool

while not f():
print(secrets.randbelow(2), end="")

for byte in itertools.zip_longest(
*(iter(bin(int.from_bytes(code, "big"))[2:]),) * 8, # bits in a byte
fillvalue = 0):
print("".join(byte), end="")


Try it online!

• cracked – pppery Jul 26 '17 at 15:18
• eval`ing code directly from input without error handling is a trivial way to get cracked – pppery Jul 26 '17 at 15:20
• @ppperry Rematch? – wizzwizz4 Jul 26 '17 at 15:36