222
\$\begingroup\$

Try to write some code in your language and make it not satisfying our criteria of being a programming language any more.

A language satisfies our criteria (simplified version for this challenge) of being a programming language if:

  • It can read user input representing tuples of positive integers in some way.
  • It can output at least two different possible results depending on the input.
  • It can take two positive integers and add them (and the result can affect the output).
  • It can take a positive integer and decide whether it is a prime (and the result can affect the output).
  • For the purpose of this challenge, any kind of output that isn't an allowed output method for a normal challenge is ignored. So it doesn't matter whether the program can also play a piece of music, or posting via HTTP, etc.
  • Update: You can also choose one or some of the allowed output methods, and ignore all the others. But you must use the same definition everywhere in the following criteria. And if your program can disable more than one output methods — that worths more upvotes.

Examples like making it not able to output, or disabling all the loop constructs so it won't be able to do primality test and making sure the user cannot re-enable them.

You should leave a place for inserting new code. By default, it is at the end of your code. If we consider putting the source code in that place in your answer and running the full code as a complete program the interpreter of a new language, that language should not satisfy the criteria.

But the inserted code must be executed in such a way like a language satisfying the criteria:

  • The inserted code must be grammatically the same as something (say it's a code block in the following criteria) that generally do satisfy the criteria, from the perspective of whoever wants to write a syntax highlighter. So it cannot be in a string, comment, etc.
  • The inserted code must be actually executed, in a way it is supposed to satisfy the criteria. So it cannot be in an unused function or sizeof in C, you cannot just execute only a non-functional part in the code, and you cannot put it after an infinite loop, etc.
  • You can't limit the number of possible grammatically correct programs generated this way. If there is already something like a length limit in the language you are using, it shouldn't satisfy the criteria even if this limit is removed.
  • You can't modify or "use up" the content of input / output, but you can prevent them from being accessed.
  • These criteria usually only applies to languages without explicit I/O:
    • Your code should redirect the user input (that contains informations of arbitrary length) to the inserted code, if a code block isn't usually able to get the user input directly / explicitly in the language you are using.
    • Your code should print the returned value of the inserted code, if a code block isn't usually able to output things directly / explicitly in the language you are using.
    • In case you print the returned value, and it is typed in the language you are using, the returned type should be able to have 2 different practically possible values. For example, you cannot use the type struct {} or struct {private:int x;} in C++.

This is popularity-contest. The highest voted valid answer (so nobody spotted an error or all errors are fixed) wins.

Clarifications

  • You shouldn't modify the code in the text form, but can change the syntax before the code is interpreted or compiled.
  • You can do other things while the code is running. But the reason that it doesn't satisfy the criteria should be within the inserted code itself. It can error because of the interference of another thread, but not just be killed by another thread.
  • All the specs basically means it should be grammatically likely satisfying the criteria if all the built-ins were not changed but not actually do. It's fine if you find any non-grammatical workarounds, such as passing the parameters to the code block correctly, but make them not able to be used in some way.
  • Again, the inserted code must be actually executed. Code after an infinite loop or crashing is considered "not actually executed", thus not valid. Those answers might be interesting, but there are already some other infinite loop or crashing questions on this site, and you may find a more appropriate one to answer. If not, consider asking a new question. Examples of those questions are:

Leaderboard

var QUESTION_ID=61115/*,OVERRIDE_USER=8478*/;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,/*getComments()*/(more_answers?getAnswers():process())}})}/*function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}*/function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),score:s.score,language:a[1],lang:jQuery('<div>').html(a[1]).text(),link:s.share_link})}),e.sort(function(e,s){var r=e.score,a=s.score;return a-r});var s={},r=1,a=null,n=1;e.forEach(function(e){e.score!=a&&(n=r),a=e.score,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",e.n=n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.score).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text())/*,s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}*/});var t=e/*[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o])*/;t.sort(function(e,s){return (e.lang.toUpperCase()>s.lang.toUpperCase())-(e.lang.toUpperCase()<s.lang.toUpperCase())||(e.lang>s.lang)-(e.lang<s.lang)});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{PLACE}}",o.n).replace("{{LANGUAGE}}",o.language).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.score).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<(?:h\d|(?!.*<h\d>)p)>\s*((?:[^,;(\s]| +[^-,;(\s])+)(?=(?: *(?:[,;(]| -).*?)?\s*<\/(h\d|p)>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;float:left}table{width:250px}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=7509797c03ea"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Sorted by Language</h2> <table class="language-list"> <thead> <tr><td></td><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{PLACE}}</td><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
46
  • \$\begingroup\$ Am I allowed to change the code before executing it? Also, can I run other code whilst I am running the code given? \$\endgroup\$
    – Blue
    Commented Oct 18, 2015 at 12:30
  • 26
    \$\begingroup\$ This could have made a really great cops and robbers challenge I think. \$\endgroup\$
    – DankMemes
    Commented Oct 18, 2015 at 23:07
  • 6
    \$\begingroup\$ @DankMemes Agreed. As it stands, it's much too vague, and most answers would be invalidated by finding a workaround. CnR with this premise would be delightful. \$\endgroup\$
    – user45941
    Commented Oct 18, 2015 at 23:54
  • 3
    \$\begingroup\$ So then it seems to be saying that in languages with explicit IO it's permissible to do completely boring things like reading and discarding the contents of stdin. It sets up a completely unfair playing field where some languages require you to carefully handle the IO for the inserted code, and other languages allow you to trash it and deny IO to the inserted code. \$\endgroup\$ Commented Oct 19, 2015 at 12:28
  • 6
    \$\begingroup\$ Are we allowed to use a language that's already unusable to begin with? (JavaScript for example) \$\endgroup\$
    – 12Me21
    Commented Oct 17, 2017 at 14:23

92 Answers 92

8
\$\begingroup\$

JavaScript in browser

Well, at least in IE11.

window.addEventListener("error", function(){});
document = document.write = alert = prompt = confirm = console = void(
    (function (window) {
        try {
            //Code goes here
        } catch (e) {}
    })({})
);

Disables writing to the document, writing to the global variable and returning from the function.

Comment if I've missed out an output method!

\$\endgroup\$
11
  • \$\begingroup\$ Exceptions will still show in the console. You can handle those by doing window.addEventListener('error',function(){}); \$\endgroup\$ Commented Oct 18, 2015 at 19:19
  • \$\begingroup\$ @IsmaelMiguel Now I can't take all the credit! d;-D \$\endgroup\$
    – wizzwizz4
    Commented Oct 18, 2015 at 19:24
  • 5
    \$\begingroup\$ Does this seriously work? That makes no sense at all: document should still be accessible from the outer scope in the inserted code, and it shouldn't get replaced until after the inserted code has finished executing. \$\endgroup\$ Commented Oct 18, 2015 at 20:46
  • 2
    \$\begingroup\$ It's not easy \$\endgroup\$ Commented Oct 19, 2015 at 21:02
  • 2
    \$\begingroup\$ Ran this in console, then tried to upvote it... \$\endgroup\$
    – emanresu A
    Commented Apr 5, 2021 at 0:48
8
\$\begingroup\$

Hoon

=<  ~
(your code)

Hoon is a odd. It's pretty much entirely unlike other programming languages, not only in syntax but in semantics. Unlike languages like Hexagony, though, it wasn't made to be purposely esoteric.

Hoon compiles to Nock, a minimal combinator based VM. Nock is stupid: the spec can be gzipped to 340 bytes. The only math operation is incrementing. Everything is a noun: an atom (bignum) or a cell (pair of nouns), with the entire memory model arranged in an immutable acyclic binary tree. The only output is the noun that your expression reduces to.

Because of the weird compilation target, Hoon is also weird: it's completely pure. Hoon compiles down to a Nock expression that is evaluated on a "context". The entire kernel and stdlib, along with all variables, are passed implicitly to the program by the context.

To make Hoon unusable we just use =<, which is "evaluate a in the context of b". We are always evaluating ~, which is zero. No matter what b does, it can't change the value it reduces to, and since it can't have side effect it can't do input or output.

Side note: Since you can't actually prompt for input from Hoon (purity!), by the rules it isn't actually a programming language. Input is via function arguments, output via return values (or ~&, which is more of a printf debugging feature and is transparent to the program).

For a program to get input in Urbit, you actually write a program that return a function that accepts input, and the shell asks on your behalf and passes to the callback.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Definitely a programming language by our standards, though \$\endgroup\$
    – cat
    Commented Oct 1, 2016 at 10:41
7
\$\begingroup\$

GolfScript

"#{def eval(s) end}":+:%:/:,:*:do:while:until

The series of :foo replaces all of the looping operators and addition and concatenation, but that's not sufficient. It's also necessary to prevent deferring the computation to Ruby's string interpolation, which I accomplish by replacing Ruby's eval operator using a string interpolation. String literals which occur later in the source code will be passed through my no-op eval rather than the built-in one.

The reason it's necessary to replace all of the looping operators, even such innocuous ones as ,, is that primality testing doesn't require unbounded looping. E.g. the following uses only , in its three forms (range, filter, len) to do primality testing:

~.,2>{1$\%!},,\;

The reason for replacing + is that jimmy23013 proposed using quining to get a looping construct. The specific implementation he provided doesn't work because by clobbering foo I've also clobbered the (standard) interpreter's way of parsing strings, but I expect it could be reworked using blocks instead of strings so I'm playing it safe.

\$\endgroup\$
8
  • \$\begingroup\$ Primality test is still possible: ~.1>2\'3$3$\'@2$-@@2$0>!.+.+.+.+.+.+>.~\'.~;;!!@&@)\@3$3$>.+.+.+.+.+.+.+>.~'.~;\;\;. Without eval strings and numbers can't be specified directly, but there are workarounds like n[n!!.+.+.+.+.+.+]+. \$\endgroup\$
    – jimmy23013
    Commented Oct 22, 2015 at 12:01
  • \$\begingroup\$ Seems to give an error in the online tester; I'll try it at home later. Is the idea basically to use a quine technique to get a loop? \$\endgroup\$ Commented Oct 22, 2015 at 12:37
  • \$\begingroup\$ Yes. It doesn't work with "#{def eval(s) end}" directly and need some more complex workaround, which I'm not bothered to implement yet. \$\endgroup\$
    – jimmy23013
    Commented Oct 22, 2015 at 14:51
  • \$\begingroup\$ Why not just block ~? Those .+.+... can be replaced with 1000 0 if. \$\endgroup\$
    – jimmy23013
    Commented Oct 25, 2015 at 14:37
  • 1
    \$\begingroup\$ Why not just block everything...? \$\endgroup\$
    – lynn
    Commented Dec 29, 2015 at 2:11
7
\$\begingroup\$

Forth

0 set-order

Basically, tell the interpreter/compiler that there are no dictionaries of known instructions. It can still read numbers (because they're not instructions) and they'll go on the stack if interpreting, but you can not issue any instructions about what to do with them, nor can you restore the search order because that would require issuing an instruction.

\$\endgroup\$
7
\$\begingroup\$

INTERCAL-72

DO ABSTAIN FROM NEXTING+REINSTATING

INTERCAL has a command for globally disabling the ability of other types of commands to run. (Using it in this form is generally considered a bad idea, because it's a global action-at-a-distance which has no way to exactly reverse it; more recent versions of INTERCAL also have ABSTAIN #1 FROM which is exactly reversed by REINSTATE, but that wasn't around in the time of INTERCAL-72, the oldest version of the language.)

ABSTAINING from REINSTATING is an even worse idea, because it then becomes impossible to even approximately reverse the effect of the ABSTAIN; you can't do a global REINSTATE (the crudest way to get the commands working again) if you can't do any sort of REINSTATE. All we have to do, therefore, is to disable enough other commands at the same time that the language becomes impossible to program in. INTERCAL-72 only has one useful control structure (NEXT/RESUME/FORGET), and disabling NEXT by itself is enough to make it impossible to do any sort of loop.

In more modern versions of INTERCAL, there are a ton of other ways to do control flow (COME FROM, WHILE (not the same as C's while!), TRY AGAIN, GO AHEAD, etc.), and even other ways to reinstate lines of code (e.g. AGAIN), so an answer in modern INTERCAL, while it could use the same general idea, would be a lot longer.

\$\endgroup\$
6
\$\begingroup\$

Z80 assembler

Two bytes are enough to completely hang any Z80 based system:

di 
halt

aka "Disable interrupts, then halt until an interrupt arrives". Yeah, sure!

EDIT: I had missed the "code that crashes doesn't count" part in the question, so I guess that this does not qualify.

\$\endgroup\$
1
6
\$\begingroup\$

Go

I did it! I really finally did it! I've been stewing on this problem for months but I finally have a definitive solution that I challenge anyone to crack!

package main

import (
    . "runtime"
    . "os"
)

func main() {
    const (
        Chmod = iota
        Chtimes
        Create
        Exit
        File
        FindProcess
        Lchown
        Link
        Mkdir
        MkdirAll
        NewFile
        Open
        OpenFile
        Process
        Remove
        RemoveAll
        Rename
        Setenv
        StartProcess
        Symlink
        TempDir
        Truncate
        Unsetenv
    )
    Stdout.Close()
    Stdin.Close()
    Stderr.Close()
    defer func() {
        go func() {
            // User code here
        }()
    }()
    Goexit()
}

My definitive reddit post on this problem for Go.

But now, I have a solution. By forcing the user's code to execute in a goroutine, and then terminating the main goroutine with runtime.Goexit, the user can no longer set the exit code. If they panic the program crashes, yes, but if they don't then it also crashes, per the documentation of Goexit:

Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.

\$\endgroup\$
3
  • \$\begingroup\$ I give up, omfg \$\endgroup\$
    – cat
    Commented Oct 1, 2016 at 10:46
  • \$\begingroup\$ @cat Nonverbal communication can be hard to understand at times. Are you impressed, or annoyed that I have continued to notify you about my progress on this challenge? \$\endgroup\$
    – EMBLEM
    Commented Oct 19, 2016 at 20:26
  • 1
    \$\begingroup\$ I'm genuinely sorry, I guess I should have appended a :D -- I'm impressed, and only cheerfully annoyed at your awesome answer c: I don't mind you keeping me updated. \$\endgroup\$
    – cat
    Commented Oct 19, 2016 at 21:47
6
\$\begingroup\$

Mascarpone

0^

Mascarpone is a language that is quite similar in concept to Emmental, but taken to the extreme. Interpreters are first class objects, so you can push interpreters to the stack, modify them, and then use them on program strings.

In this case, the initial interpreter assigns 0 the meaning of "push to the stack an interpreter in which every character is defined to cause an error." ^ is assigned the meaning of "pop an interpreter off the stack and assign it as the new interpreter for subsequent characters in the program." This means that any characters added after this will error.

Alternatively, if this violates the "code must actually execute" rule, there are many other ways to break the language.

v'_>1^

This is similar, but instead of defining every character to be an error, it defines every character to be a no-op. That way, every character of your code is technically executed, but it just has no effect.

Here's another way:

v'_v>'x<^

x should be replaced with a command here. This essentially creates a new version of the current interpreter with x redefined to be a no-op, and then assigns that as the new interpreter.

While disabling commands might seem devastating, Mascarpone actually seems fairly flexible to the removal of individual commands.

  • It only really needs [v*:! to simulate the Turing-complete ():^ subset of Underload.
  • ' can be used instead of [, so disabling it doesn't kill the language.
  • Disabling . (the output instruction) doesn't work, as you can still output via exit code (erroring/not erroring).
  • Instead of ! (execute operation), you can have v'_<^_ (assign the operation to a command in a new interpreter, then switch to that interpreter and run that command).

I believe disabling v, *, or : might kill the language, but this is only 3 commands out of 18.

\$\endgroup\$
6
\$\begingroup\$

ForceLang

def io nil
def gui nil
def require nil
def goto nil
def gotoex nil
def if nil
def undef nil
def def nil
<your code here>

Uses def to mask a bunch of key stuff, including all of the language's IO and most of the language's control flow. Then uses def to mask undef so you can't undo any of it. Finally, uses def to mask itself just because it can.

\$\endgroup\$
6
\$\begingroup\$

Java

I decided to do something little bit nasty and break java, by using little bit less code than here

       public class a {
        
            static {
                final SecurityManager securityManager = new SecurityManager() {
                    @Override
                    public void checkPackageAccess(String pkg) {
                        throw new RuntimeException("broken");
                    }
                };
                java.lang.System.setSecurityManager(securityManager);
        
            }
        
            public static void main(String[] args) throws Exception {
             //and here goes your code...
        
            }
        }
\$\endgroup\$
9
  • \$\begingroup\$ You know, I can just do this. Not sure if that counts though. \$\endgroup\$ Commented Jun 2, 2019 at 0:29
  • \$\begingroup\$ I don't think that counts as a crack. \$\endgroup\$ Commented Sep 4, 2019 at 22:10
  • \$\begingroup\$ @BenjaminUrquhart fair point, fixed \$\endgroup\$
    – user902383
    Commented Sep 5, 2019 at 6:55
  • 1
    \$\begingroup\$ If you wish to subject your answer to "cracks" that consist of adding code to the end (which I don't think are valid), then your fix can still be worked around. \$\endgroup\$ Commented Sep 11, 2019 at 1:46
  • \$\begingroup\$ Found a "crack" that is contained within the main function. Takes 2 ints as arguments and outputs to stderr via an exception with a message set to the sum of those values. Will link once I can find a way to make it fit in a comment. \$\endgroup\$ Commented Sep 15, 2019 at 21:06
6
\$\begingroup\$

HP48 calculator family

OFF

Turns the calculator off.

\$\endgroup\$
5
\$\begingroup\$

Python

#Run the following in Python IDLE (spoiler: don't)
import os, shutil, sys
try:shutil.rmtree(os.path.split(sys.executable))
except:pass
os.system("python")

This functions by deleting most of the Python interpreter. Then it recursively starts itself. Any code you type afterward will fail horrendously.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Does this really work in IDLE? Because in the normal REPL on my system, os.path.split(sys.executable) -> ('/usr/bin', 'python3'). And /usr/bin is only writable by root… \$\endgroup\$ Commented Oct 21, 2015 at 19:03
  • 3
    \$\begingroup\$ @BlacklightShining maybe you're running in root to begin with. Anyway, my sacrifical system ran Windows, which is decidedly stupider about such things. \$\endgroup\$
    – geometrian
    Commented Oct 21, 2015 at 21:16
  • 5
    \$\begingroup\$ It meets the asker's criteria, then. I'm still not sure I like it personally, though, given that it only breaks the language if the system has insane permissions… \$\endgroup\$ Commented Oct 22, 2015 at 5:33
5
\$\begingroup\$

Javascript

Tested in Chrome.

Object.defineProperty(document,"body",{get:function(){return null}});
Object.defineProperty(document,"innerHTML",{set:function(){}});
Object.defineProperty(HTMLElement.prototype,"innerHTML",{set:function(){}});
Object.defineProperty(HTMLElement.prototype,"innerText",{set:function(){}});
HTMLElement.prototype.appendChild=document.createElement=document.getElementsByName=document.getElementsByClassName=document.getElementsByTagName=document.getElementsByTagNameNS=document.getElementById=document.write=document.writeln=console=document.querySelector=document.querySelectorAll=alert=setTimeout=prompt=confirm=open=Array=Array.prototype.constructor=Object=Object.prototype.constructor=Object.prototype.toString=null;
try{var window = {}; with(window){/*code*/} }catch(e){}

Browser javascript is really hard to break.

\$\endgroup\$
9
  • \$\begingroup\$ document.body.innerHTML="<iframe src=\"javascript:'<script>alert(prompt(\\\'Hello!\\\',\\\'\\\'));</script>'\">" \$\endgroup\$ Commented Oct 20, 2015 at 23:22
  • \$\begingroup\$ @user2428118: Fixed! \$\endgroup\$ Commented Oct 21, 2015 at 1:36
  • \$\begingroup\$ Is it intentional that this immeadetly redirects the browser's location to 'null'? \$\endgroup\$ Commented Oct 21, 2015 at 20:28
  • \$\begingroup\$ No, it isn't. Let me fix that. \$\endgroup\$ Commented Oct 21, 2015 at 20:30
  • \$\begingroup\$ setTimeout('throw "Test"',10) works for output too. Also window.open('data:text/html,a%20div'). \$\endgroup\$ Commented Dec 6, 2015 at 22:06
5
\$\begingroup\$

Javascript

You can stop any output destroying (most of) the window object.

Also, you can't get rid of document, but you can crush it's content every millisecond.

Here's what I came up with:

(function(window){
    var html = document.getElementsByTagName('html')[0];
    
    setInterval(function(){html.innerHTML='';}, 1);
    window.addEventListener('error', function(){});
    
    for(var k in window)
    {
        if(k!='location')
        {
            window[k]=window;
        }
    }
})(Function('return this')());

This sets every single object inside window (except location, it will reload the page) to be ... the window object!!!

This will mess directly with the real window: Running Function('return this')() will return the this object for that context. Since that is eval'ed code, it will be the ... window object!

This also catches all exceptions by setting an handler on window, before deleting everything.

Also, we go grab the <html> element and set it's innerHTML to an empty string. This means that your output will work for less than a millisecond.

Your code is still executed. It just won't be able to show any output. Maybe you can create a file! If only the API wasn't destroyed...


Warning: This causes huge strain on your CPU and RAM. Run this at your own risk! It may cause overheating on your CPU and abnormal behaviour on your browser. It forces the code to run as many times as the browser can handle, in a second. This may cause a huge queue of functions to be executed, if it takes longer than the minimum time interval (which is 4ms for Firefox and Google Chrome (source provided by @somebody))

To stop the process, either run document.location=document.location or press F5.

I am NOT responsible for ANY hardware or software damage or data loss caused by running this code.

\$\endgroup\$
7
  • \$\begingroup\$ Most browsers don't support intervals less than about 10ms. \$\endgroup\$ Commented Dec 6, 2015 at 12:48
  • \$\begingroup\$ @SuperJedi224 What browsers? It works everywhere where I try it \$\endgroup\$ Commented Dec 6, 2015 at 14:24
  • \$\begingroup\$ I heard somewhere that there was a minimum of 10ms in chrome and 15ms in FF and safari. Apparently, this is no longer the case. However, there is still a minimum of 4ms with nested timeouts and 1s in tabs that are not currently focused. \$\endgroup\$ Commented Dec 6, 2015 at 18:43
  • \$\begingroup\$ @SuperJedi224 But there aren't nested timeout. They seem to work fine on any browser I throw this at. If this worked only on a single version of a very specific browser, it was acceptable. Watch the most voted answer: it only works on a specific engine, in a specific version. \$\endgroup\$ Commented Dec 6, 2015 at 19:11
  • \$\begingroup\$ What I meant is that the information on which I had based my first comment was apparently outdated. \$\endgroup\$ Commented Dec 6, 2015 at 19:15
5
\$\begingroup\$

IBM Mainframe Assembler - 6

la 15,0

On entry to any program, Register 15 contains your base address. Overwrite that value, and expect an 0C4 abend (addressing exception) almost immediately.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Welcome to the site! \$\endgroup\$
    – DJMcMayhem
    Commented May 5, 2017 at 20:58
  • 4
    \$\begingroup\$ That appears to be 7 bytes. \$\endgroup\$ Commented Jul 10, 2017 at 22:00
5
\$\begingroup\$

Operation Flashpoint scripting language

A feature I once discovered accidentally: You can create a variable with a name that's already taken by a command, thus making the command inaccessible. It can be recovered from by deleting the variable, but the command that is used to remove a variable can also be overwritten.

Save the following as init.sqs in the mission folder:

; Overwrite commands that can be used to execute code with variables with the same name.
call = 0
exec = 0
drop = 0
addEventHandler = 0
createDialog = 0

; There are other commands that could do the task, but not without input from the player.
; Any command in the game can be overwritten (except operators whose name doesn't begin
; with a letter, those are not valid variable names), so to be completely sure one could
; overwrite every single command, but these should suffice.

; Even if somehow ("onFlare.sqs", "onPlayerKilled.sqs" or some other scripts that are called
; automatically under specific circumstances) one gets a script running, make it impossible
; to create loops. Recursion is only possible with 'exec' or 'call' (and technically with 'drop').
goto = 0
while = 0
forEach = 0

; Overwrite the 'nil' command so that it cannot be used to recover from the above.
; Without this, "call = nil" would make 'call' work again (or any other overwritten command).
nil = 0

; Your code can be added here at the end of this script or anywhere else in the mission.

Now there is no way to use any kinds of loops or recursion.

Trying to call a piece of code outputting "Hello, World!":

enter image description here

\$\endgroup\$
5
\$\begingroup\$

Python 2

import sys
sys.setrecursionlimit(1)

Sets the maximum recursion depth to 1.
After entering these 2 lines, any subsequent line will yield:

RuntimeError: <exception str() failed>

enter image description here

Edit: They fixed this bug in Python 3.

Python 3

import sys,os,_thread

def poll(id):
    while True:
        sys.stdout = None
        sys.__stdout__ = None
        sys.stderr = None
        sys.__stderr__ = None
        open = None
        os.system = None
        builtins = None

_thread.start_new_thread(poll, (1,))

Print will now output nothing. Any other command that creates output gives:

RuntimeError: lost sys.stdout

enter image description here

Edit: The sys.__stdout__ = None serves to prevent the user from recovering sys.stdout using sys.stdout = sys.__stdout__. Credit to @someone.

Edit: sys.stdout could also be redirected to a file using sys.stdout = open("output.txt","w"). The open = None prevents this. Credit to @someone.

Edit: Added os.system = None because it could also be used to print. Credit to @Jonathan Frech

def print(x):
    os.system("echo {0}".format(x))

Edit: open can be recovered by:

import builtins
open = builtins.open

To prevent this, I made the whole script into a thread.

Edit: Added builtins = None to disable builtins.open. Credit to @Jonathan Frech

\$\endgroup\$
8
  • \$\begingroup\$ Can sys.stdout = sys.__stdout__ recover python 3 version? \$\endgroup\$ Commented Oct 22, 2017 at 6:10
  • \$\begingroup\$ @someone Indeed. Setting it to None as well seems to do the trick :) \$\endgroup\$ Commented Oct 22, 2017 at 6:17
  • \$\begingroup\$ Can we output to a file with sys.stdout = open("abc.txt","w")? \$\endgroup\$ Commented Oct 22, 2017 at 6:24
  • \$\begingroup\$ Outputting text is most likely still possible using os.system. \$\endgroup\$ Commented Oct 22, 2017 at 19:44
  • \$\begingroup\$ I think your last edit should say sys.stdout instead of sys.stdin. \$\endgroup\$ Commented Oct 23, 2017 at 0:29
5
\$\begingroup\$

Batch Prompt, 7 bytes

cmd>NUL

Regardless of the command entered, it will disappear into the NUL abyss.

\$\endgroup\$
4
\$\begingroup\$

StackStream

{ new-stream }     'stdinout def
{ drop exec }      'if def
{ drop drop exec } 'elseif def

Basically, this redefines the default symbol 'stdinout' to return an empty stream, which points nowhere. It then defines 'if' and 'elseif' to always run the first branch, so output is always the same.

\$\endgroup\$
4
\$\begingroup\$

TeX (LaTeX)

\output{\setbox1\vbox{\unvbox255}}}
\let\output\relax

You can still do a lot in a code that starts with this. However, no pages will be ever produced. The output routine that takes care of building up the pages is destroyed, and also its "handle" is destroyed so that you cannot rebuild it. Needless to say, you can still compute a lot of stuff and output them in a file or in the log; you just can't use this crippled TeX to produce any document.

To disable writes, you can simply add:

\let\write\relax

You can't disable the log though.

\$\endgroup\$
4
\$\begingroup\$

TXR Lisp

(set *package* (make-package "X")*package-alist*())

The TXR Lisp dialect has a package system that is inspired by the one in ANSI Common Lisp. TXR Lisp not only has the variable *package*, but also exposes the list of packages themselves as the special variable *package-alist*, which can be assigned, or subject to a dynamic binding.

If we change *package* to a new, empty package, we can still reach functions in the usr package:

1> (set *package* (make-package "empty"))
#<package: empty>
2> (+ 2 2)
** warning: (expr-2:1) unbound function +
** (expr-2:1) + does not name a function or operator
3> (usr:+ 2 2)
4

However, if we also clear the *package-alist*, we will prevent the usr: prefix from being usable:

4> (usr:set usr:*package-alist* usr:nil)
nil
5> (usr:+ 2 2)
expr-5:1: usr:+: package usr not found
** syntax error

Of course, we should do this manipulation first, then clobber *package*, or do it all in one set form:

After this is evaluated, the rest of the code is in an inescapable, empty sandbox.

\$\endgroup\$
4
\$\begingroup\$

Bash, 60 bytes

shopt -s extdebug;f(){ return 1;};declare -rf f;trap f DEBUG

Your code goes afterwards. I abused this answer which uses a debugging feature. The return code of the function determines what to do with the original command.

I had to add the declare -rf f; bit to make the function read-only. This addresses @Gilles workaround.

I think this complies with the rules since code is still being taken in by the interpreter as the next command without infinite loops, crashing, etc.

Let me know if there is another workaround.

\$\endgroup\$
0
4
\$\begingroup\$

QBasic, 29 bytes

FOR i=0TO65535:POKE i,0:NEXT

Overwrites current segment (containing code and important data structures of the interpreter) with zeros.

Similar code may have similar effects on most interpreted BASIC implementations running on bare metal.

\$\endgroup\$
4
\$\begingroup\$

Pyth (in safe mode)

D
;Dp;

Just redefines both methods of printing with the wrong arity, any attempt to print will now crash the interpreter, including implicit prints.

\$\endgroup\$
0
3
\$\begingroup\$

Simplex v.0.5

h]$g$o$s$`$$u1{vbR4Rl<?[{;L}#]{p}u}
h]                                   ~~ define macro 0 as nothing
  $ $ $ $ $                          ~~ grab next character and redefine its function to
                                     ~~ evaluate the current macro number (0)
   g o s ` $                         ~~ redefine output as a string (g), output as number 
                                     ~~ (o), as a character (s), or as a result of
                                     ~~ suppression (`) and also prevents the user from
                                     ~~ redefining them back, if possible
            u1                       ~~ goes up a strip and sets the byte to 1
              {                   }  ~~ repeat inside until a zero byte is met
               v                     ~~ goes down a strip
                b                    ~~ takes input as a string and puts to strip
                 R4Rl<               ~~ right, 4, right, length => length < 4
                      ?[     ]       ~~ perform inside iff byte is not zero
                        {  }         ~~ loop inside until zero byte is met
                         ;L          ~~ pushes the character to the outer program, left
                            #        ~~ stops evaluation (goes to outer program)
                              { }    ~~ loop inside until zero byte is met
                               p     ~~ removes current byte
                                 u   ~~ goes up a strip to meet the 1 byte; essentially
                                     ~~ a while(true){...} loop.

Essentially, destroys the output commands, then takes input from the user as strings, pushing them to the outer program, until a null-length string is encountered, at which point evaluation ceases and the user's input (the outer program) is evaluated. The user cannot output anything nor can they redefine anything. This thus eliminates the criteria of being able to output anything. If you want to eliminate input, simply put a $ in front of each of G, b, and i before the octothorpe (#) 6 characters before the end.

\$\endgroup\$
3
\$\begingroup\$

Perl

Not only will this make perl unusable, but your entire machine will seize up in seconds... Also works well for bash.

while(fork){fork}

Because fork returns the PID of the child process, or zero for the parent, evaluation the first-fork will create two processes. One of those will exit the loop, and continue evaluation. The other will enter the while body, and create one additional new process with the second-fork. These two processes will again hit the first-fork and create and additional two processes, for a total of four. Two of those will exit the while loop, and execute following code a second and third time. The other two will again enter the loop body. Then four processes will be tested in the first-fork, creating 8 processes, four of which execute the following code for a 4th, 5th, 6th and 7th time. And so on.

On any unix system, you run out of PID numbers and the fork begins to fail when you have 32k processes, but at this point, the scheduler is so busy that any interaction with a windowing system or shell is unusably slow.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Is the code after that actually executed? \$\endgroup\$
    – jimmy23013
    Commented Dec 1, 2015 at 8:10
  • \$\begingroup\$ @jimmy23013 good question. The answer is yes; I updated my response to reflect this. \$\endgroup\$ Commented Dec 1, 2015 at 21:10
  • 15
    \$\begingroup\$ In all fairness, Perl is unusable out of the box. \$\endgroup\$
    – user45941
    Commented Dec 1, 2015 at 21:14
  • 3
    \$\begingroup\$ What if your code includes kill(getppid())? \$\endgroup\$ Commented Jun 18, 2016 at 12:03
3
\$\begingroup\$

Common Lisp

(setq *debugger-hook* (lambda (a b) (abort)))

(set-macro-character #\( (lambda (stream char)
                           (read-delimited-list #\) stream)
                           (values)))

Step one is to disable the debugger. I do this by binding the *debugger-hook* (which is called immediately before entering the debugger) to a function which cancels whatever tried to enter the debugger in the first place. Then, I turned ( into a comment character- everything up to its matching close paren is completely ignored.

The result, tested on sbcl at the repl (both line-by-line and #'load ing it from a file), is a repl which completely ignores any meaningful code. Literal values (number, strings, symbols, etc.) work just fine, but anything else is just ignored.

\$\endgroup\$
1
  • \$\begingroup\$ What old-paren? \$\endgroup\$ Commented Jul 10, 2017 at 21:41
3
\$\begingroup\$

Funky

for v in values({math, string, table, io, _G})
    for k in keys(v)
        v[k] = nil

This nukes the math functions, then the string, table, and IO functions, and finally, cleans out the _G table.

The math functions are actually what's called when operators are used, so without them, most functionality is gone. But you can do math with table functions, if you get smart, so they're nuked too.

When the _G table is cleared, all forms of IO are finally also gone, and the getMetaFunc function is also nuked, which causes errors if most things happen.

After this, the language is entirely unusable.

Try it online!

\$\endgroup\$
3
\$\begingroup\$

PowerShell

(gv ex* -v|% S*).LanguageMode=2

This doesn't work on TIO (which uses PowerShell core) but it does work on Windows PowerShell. Additional code can (attempt to) be executed directly after this (via ; or newline).

Putting PowerShell into NoLanguage mode makes it effectively useless unless you pre-defined allowable commands to execute.

\$\endgroup\$
2
  • \$\begingroup\$ No need to count bytes. \$\endgroup\$
    – user75200
    Commented Oct 29, 2017 at 16:49
  • \$\begingroup\$ @user75200 true, fixed \$\endgroup\$
    – briantist
    Commented Oct 29, 2017 at 21:13
3
\$\begingroup\$

Rust

macro_rules! toilet{
  ($($_:tt)*)=>{}
}

fn main(){
  toilet!{
    Your code goes here.
  }
}

Try it online!

I defined a toilet macro that causes the compiler to delete any code inside of it. Anything, including the main function, can be deleted in this manner.

use std::alloc::{GlobalAlloc,Layout};
struct EvilAlloc{}
unsafe impl GlobalAlloc for EvilAlloc{
  unsafe fn alloc(&self,_:Layout)->*mut u8{
    std::ptr::null_mut()
  }
  unsafe fn dealloc(&self,_:*mut u8,_:Layout){}
}
#[global_allocator]
static EVIL: EvilAlloc = EvilAlloc{};
//your code here

Try it online!

This one creates and sets a malicious global allocator that will always fail or leak memory.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.