狂気チェックプログラム


16

狂気:同じことを何度も繰り返し、異なる結果を期待する。

実行するたびに例外(実行時エラー)をスローするだけのプログラムを作成します。課題は、例外を直接呼び出さずに(throwステートメントなしで)複数のクラッシュを生成する可能性があり、組み込みのランダムまたはCPUティックカウント関数を使用しないことです。

  • 考えられるエラーごとに10ポイント
  • エラー/クラッシュが別のプロセスまたはシステムで発生した場合、25ボーナスポイント

ルール

  1. 応答では、発生する可能性のあるエラーとその生成方法を示す必要があります。
  2. プログラムを実行するたびに同じ番号でシードされない限り、システム(組み込み)乱数ジェネレーターを使用できません。
  3. メインプログラムスレッドの開始に対して相対的にカウントされない限り、ティックまたはCPUサイクルの数は使用できません。
  4. マルチスレッドが許可されます(推奨されない場合)。

編集1

  1. GUIDの生成は、組み込みの乱数ジェネレーターに分類されます。カスタムの「自家製」GUID生成が許可されています。

  2. ファイルシステムへのアクセスは、ルールをバイパスする(ランダムビットのファイルまたはタイムスタンプを読み取る)場合を除き、ファイルのI / Oで許可されます。

編集2

  1. 非常識なソフトウェアを作成するという挑戦の精神を呼び出しabort()たり、assert()違反したりするため、この失敗モードに対して10ポイントは与えられません。

幸運を!


GUIDの生成はランダムと見なされますか?
ミクロ

良い質問。エントロピーは、人為的ではなく、魔法のように(カードの家のコード)達成する必要があると思うので、GUIDにはノーと言います。
ja72 14年

JSの場合-クラッシュしたブラウザーは25ボーナスとしてカウントされますか?コードをテストするブラウザを選択できますか?
18:30に14年

ホスト(ブラウザーまたはフレームワーク)をクラッシュさせると、25のボーナスポイントが付与されます。ただし、常にクラッシュする必要があります。
ja72 14年

問題は、非決定的手段(クロックも除く)を使用せずに非決定的関数を記述することです。Cは、初期化されていないポインター参照にアクセスできる言語の1つです。したがって、私が見ている解決策は、初期化されていないポインターに基づいています。私にとって、初期化されていないポインターを使用することは、guidまたはランダムメソッドを使用するのと同じくらい良い(または悪い)です。
ミクロ

回答:


14

Java、400

Javaは多くのsとsに恵まれています(?)。単一のクラスの操作に固有のが多数あります。最も極端なケースの一つの例として、ある10以上のSは、(すべてののサブクラスであるに捧げ)、単独のクラスと私はコードを作るために時間をとっている(ほぼ)それらのすべてがスローされます。ExceptionErrorExceptionExceptionIllegalFormatExceptionFormatter

私の現在の答えは、40の異なるExceptions / Errorsを特徴としており、それらはSystem.nanoTime()整数のモジュロに応じてランダムに実行されます。

この方法は、経過時間を測定するためにのみ使用でき、システムまたは実時間のその他の概念とは関係ありません。返される値は、一定ではあるが任意の起点時刻からのナノ秒を表します(おそらく将来的には、値が負になる可能性があります)。Java仮想マシンのインスタンスでのこのメソッドのすべての呼び出しで同じ生成元が使用されます。他の仮想マシンインスタンスは異なるオリジンを使用する可能性があります。

上記の方法は、「3。ティックまたはCPUサイクルの数は、メインプログラムスレッドの開始に対して相対的にカウントされない限り使用できない」というケースに該当するため、許可する必要があります

コンパイル命令

コードを実行するには、OracleのJRE / JDKまたはOpenJDKを強くお勧めします。そうでない場合、例外の一部は参照実装の内部詳細に依存し、信頼できるフォールバックがないため、例外がスローされない場合があります。

以下のコードはjavac 1.7.0_11、で正常にコンパイルされ、すべての例外を生成しますjava 1.7.0_51

  1. このコードを実行するには、以下のコードをコピーしてUnicode対応エディター(Notepad ++など)に貼り付け、UTF-16で保存する必要があります(BOMが記述されている限り、ビッグエンディアンでもリトルエンディアンでもかまいません) 。

  2. 作業ディレクトリ(cd)をソースコードが保存されている場所に変更します(これは重要です)。

  3. 次のコマンドでコードをコンパイルします。

    javac G19115.java -encoding "UTF-16"
    
  4. そして、コードを実行します:

    java G19115
    

コードを破壊するものは何もありません。コンピューターでテスト実行したいからです。最も「危険な」コードはToBeRemoved.class、現在のフォルダー内のファイルを削除することです。それ以外は、残りはファイルシステムやネットワークには影響しません。


import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.text.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.security.*;

class G19115 {

    // The documentation says System.nanoTime() does not return actual time, but a relative
    // time to some fixed origin.
    private static int n = (int) ((System.nanoTime() % 40) + 40) % 40;

    @SuppressWarnings("deprecation")
    public static void main(String args[]) {

        /**
         * If the code is stated to be a bug, then it is only guaranteed to throw Exception on
         * Oracle's JVM (or OpenJDK). Even if you are running Oracle's JVM, there is no
         * guarantee it will throw Exception in all future releases future either (since bugs
         * might be fixed, classes might be reimplemented, and an asteroid might hit the earth,
         * in order from the least likely to most likely).
         */

        System.out.println(n);

        switch (n) {
            case 0:
                // Bug JDK-7080302
                // https://bugs.openjdk.java.net/browse/JDK-7080302
                // PatternSyntaxException
                System.out.println(Pattern.compile("a(\u0041\u0301\u0328)", Pattern.CANON_EQ));
                System.out.println(Pattern.compile("öö", Pattern.CANON_EQ));

                // Leave this boring pattern here just in case
                System.out.println(Pattern.compile("??+*"));
                break;
            case 1:
                // Bug JDK-6984178
                // https://bugs.openjdk.java.net/browse/JDK-6984178
                // StringIndexOutOfBoundsException
                System.out.println(new String(new char[42]).matches("(?:(?=(\\2|^))(?=(\\2\\3|^.))(?=(\\1))\\2)+."));

                // Leave this boring code here just in case
                System.out.println("".charAt(1));
                break;
            case 2:
                // IllegalArgumentException

                // Bug JDK-8035975
                // https://bugs.openjdk.java.net/browse/JDK-8035975
                // Should throw IllegalArgumentException... by documentation, but does not!
                System.out.println(Pattern.compile("pattern", 0xFFFFFFFF));

                // One that actually throws IllegalArgumentException
                System.out.println(new SimpleDateFormat("Nothing to see here"));
                break;
            case 3:
                // Bug JDK-6337993 (and many others...)
                // https://bugs.openjdk.java.net/browse/JDK-6337993
                // StackOverflowError
                StringBuffer buf = new StringBuffer(2000);
                for (int i = 0; i < 1000; i++) {
                    buf.append("xy");
                }
                System.out.println(buf.toString().matches("(x|y)*"));

                // Leave this boring code here just in case
                main(args);
                break;
            case 4:
                // NumberFormatException
                String in4 = "123\r\n";
                Matcher m4 = Pattern.compile("^\\d+$").matcher(in4);

                if (m4.find()) {
                    System.out.println(Integer.parseInt(in4));
                } else {
                    System.out.println("Bad input");
                }

                // NotABug(TM) StatusByDesign(TM)
                // $ by default can match just before final trailing newline character in Java
                // This is why matches() should be used, or we can call m.group() to get the string matched
                break;
            case 5:
                // IllegalStateException
                String in5 = "123 345 678 901";
                Matcher m5 = Pattern.compile("\\d+").matcher(in5);

                System.out.println(m5.group(0));

                // The Matcher doesn't start matching the string by itself...
                break;
            case 6:
                // ArrayIndexOutOfBoundsException

                // Who is the culprit?
                String[] in6 = {
                    "Nice weather today. Perfect for a stroll along the beach.",
                    " Mmmy  keeyboaardd    iisss   bbrokkkkeeen  ..",
                    "",
                    "\t\t\t     \n\n"};
                for (String s: in6) {
                    System.out.println("First token: " + s.split("\\s+")[0]);
                }

                // Culprit is "\t\t\t     \n\n"
                // String.split() returns array length 1 with empty string if input is empty string
                //                        array length 0 if input is non-empty and all characters match the regex
                break;
            case 7:
                // ConcurrentModificationException

                List<Integer> l7 = testRandom(42);
                Integer prev = null;
                // Remove duplicate numbers from the list
                for (Integer i7: l7) {
                    if (prev == null) {
                        prev = i7;
                    } else {
                        if (i7.equals(prev)) {
                            l7.remove(i7);
                        }
                    }
                }

                System.out.println(l7);

                // This is one of the typical mistakes that Java newbies run into
                break;
            case 8:
                // ArithmeticException

                // Integer division by 0 seems to be the only way to trigger this exception?
                System.out.println(0/0);
                break;
            case 9:
                // ExceptionInInitializerError
                // Thrown when there is an Exception raised during initialization of the class

                // What Exception will be thrown here?
                Static s9 = null;
                System.out.println(s9.k);

                // A bit less interesting
                Static ss9 = new Static();

                // ----
                // A class is only initialized when any of its method/field is
                // used for the first time (directly or indirectly)

                // Below code won't throw Exception, since we never access its fields or methods
                // Static s;
                // OR
                // Static s = null;
                break;
            case 10:
                // BufferOverflowException
                short s10 = 20000;
                ShortBuffer b10 = ShortBuffer.allocate(0).put(s10);

                // Boring stuff...
                break;
            case 11:
                // BufferUnderflowException
                ShortBuffer.allocate(0).get();

                // Another boring stuff...
                break;
            case 12:
                // InvalidMarkException
                ShortBuffer.allocate(0).reset();

                // Boring stuff again...
                // reset() cannot be called if mark() is not called before
                break;
            case 13:
                // IndexOutOfBoundsException
                System.out.println("I lost $m dollars".replaceAll("[$]m\\b", "$2"));

                // $ needs to be escaped in replacement string, since it is special
                break;
            case 14:
                // ClassCastException
                Class c14 = Character.class;
                for (Field f: c14.getFields()) {
                    System.out.println(f);
                    try {
                        int o = (int) f.get(c14);
                        // If the result is of primitive type, it is boxed before returning
                        // Check implementation of sun.reflect.UnsafeStaticIntegerFieldAccessorImpl
                        System.out.println(o);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 15:
                // NoSuchElementException
                List<Integer> l15 = new ArrayList<Integer>();
                Iterator i = l15.iterator();

                System.out.println(i.next());
                // Another boring one...
                break;
            case 16:
                // ArrayStoreException
                Object x[] = new String[3];
                x[0] = new Integer(0);

                // Straight from the documentation
                // I don't even know that this exists...
                break;
            case 17:
                // IllegalThreadStateException
                Thread t17 = new Thread();
                t17.start();
                t17.setDaemon(true);

                // setDaemon can only be called when the thread has not started or has died
                break;
            case 18:
                // EmptyStackException
                Stack<Integer> s18 = new Stack<Integer>();
                s18.addAll(testRandom(43));
                while (s18.pop() != null);

                // Originally ThreadDeath, which works when running from Dr. Java but not when
                // running on cmd line. Seems that Dr. Java provides its own version of
                // Thread.UncaughtExceptionHandler that prints out ThreadDeath.

                // Please make do with this boring Exception
                break;
            case 19:
                // NegativeArraySizeException
                Array.newInstance(Integer.TYPE, -1);

                // Do they have to create such a specific Exception?
                break;
            case 20:
                // OutOfMemoryError
                Array.newInstance(Integer.TYPE, 1000, 1000, 1000, 1000);
                break;
            case 21:
                // UnsupportedCharsetException

                // UCS-2 is superseded by UTF-16
                Charset cs21 = Charset.forName("UCS-2");
                CharsetEncoder ce21 = cs21.newEncoder();

                // Just in case...
                cs21 = Charset.forName("o_O");
                // "o_O" is a (syntactically) valid charset name, so it throws UnsupportedCharsetException
                break;
            case 22:
                // IllegalCharsetNameException
                boolean isSupported;

                isSupported = Charset.isSupported("o_O");
                isSupported = Charset.isSupported("+_+");
                Charset cs22 = Charset.forName("MerryChristmas!Hohoho!");

                // This is getting stupid...
                break;
            case 23:
                // NoClassDefFoundError
                File f = new File("ToBeRemoved.class");
                f.delete();

                ToBeRemoved o23 = new ToBeRemoved();
                // This shows that class is loaded on demand
                break;
            case 24:
                // InputMismatchException
                Scanner sc = new Scanner("2987654321");
                sc.nextInt();

                // Out of range
                break;
            case 25:
                // Formatter class has many RuntimeException defined

                // DuplicateFormatFlagsException
                System.out.printf("%0000000000000000000000000000000000000000000000000005%d\n", 42);
                break;
            case 26:
                // FormatFlagsConversionMismatchException
                System.out.printf("%,d\n", Integer.MAX_VALUE);

                System.out.printf("%,x\n", Integer.MAX_VALUE);
                // Thousand separator is only applicable to base 10

                System.out.printf("%(5.4f\n", Math.PI);
                System.out.printf("%(5.4f\n", -Math.PI);

                System.out.printf("%(5.4a\n", -Math.PI);
                // '(' flag is used to surround negative value with "( )" instead of prefixing with '-'
                // '(' can't be used with conversion 'a'
                break;
            case 27:
                // IllegalFormatCodePointException
                System.out.printf("%c", Character.MAX_CODE_POINT + 1);

                // Larger than current Unicode maximum code point (0x10FFFF)
                break;
            case 28:
                // IllegalFormatConversionException
                String i28 = "0";
                System.out.printf("%d", i28);

                // A boring example
                break;
            case 29:
                // IllegalFormatFlagsException
                System.out.printf("% d\n", Integer.MAX_VALUE);
                System.out.printf("% d\n", Integer.MIN_VALUE);

                System.out.printf("%+d\n", Integer.MAX_VALUE);
                System.out.printf("%+d\n", Integer.MIN_VALUE);

                System.out.printf("% +d\n", Integer.MIN_VALUE);
                // Use either ' ' or '+ ' flag, not both, since they are mutually exclusive
                break;
            case 30:
                // IllegalFormatPrecisionException
                System.out.printf("%5.4f\n", Math.PI);
                System.out.printf("%5.4a\n", Math.PI);
                System.out.printf("%5.4x\n", Math.PI);

                // Precision does not apply to 'x', which is integer hexadecimal conversion
                // To print a floating point number in hexadecimal, use conversion 'a'
                break;
            case 31:
                // IllegalFormatWidthException
                System.out.printf("%3n");

                // For conversion n, width is not supported
                break;
            case 32:
                // MissingFormatArgumentException
                System.out.printf("%s\n%<s", "Pointing to previous argument\n");
                System.out.printf("%<s", "Pointing to previous argument");

                // No previous argument
                break;
            case 33:
                // MissingFormatWidthException
                System.out.printf("%5d %<d\n", 42); // Pad left
                System.out.printf("%-5d %<d\n", 42); // Pad right

                System.out.printf("%-d\n", 42);
                // Missing width
                break;
            case 34:
                // UnknownFormatConversionException
                System.out.printf("%q", "Shouldn't work");

                // No format conversion %q

                // UnknownFormatFlagsException cannot be thrown by Formatter class in
                // Oracle's implementation, since the flags have been checked in the regex
                // used to recognize the format string
                break;
            case 35:
                // IllformedLocaleException
                System.out.printf(new Locale("ja"), "%tA %<tB %<tD %<tT %<tZ %<tY\n", new Date());

                System.out.printf(new Locale.Builder().setLanguage("ja").setScript("JA").setRegion("JA").build(), "%tA %<tB %<tD %<tT %<tZ %<tf\n", new Date());
                // Thrown by Locale.Builder.setScript()
                break;
            case 36:
                // NullPointerException
                Pattern p36 = Pattern.compile("a(b)?c");
                Matcher m36 = p36.matcher("ac");

                if (m36.find()) {
                    for (int i36 = 0; i36 <= m36.groupCount(); i36++) {
                        // Use Matcher#end(num) - Matcher#start(num) for length instead
                        System.out.printf("%3d [%d]: %s\n", i36, m36.group(i36).length(), m36.group(i36));
                    }
                }
                break;
            case 37:
                // AccessControlException
                System.setSecurityManager(new SecurityManager());
                System.setSecurityManager(new SecurityManager());
                break;
            case 38:
                // SecurityException
                // Implementation-dependent
                Class ϲlass = Class.class;
                Constructor[] constructors = ϲlass.getDeclaredConstructors();
                for (Constructor constructor: constructors) {
                    constructor.setAccessible(true);
                    try {
                        Class Сlass = (Class) constructor.newInstance();
                    } catch (Throwable e) {
                        System.out.println(e.getMessage());
                    }
                    // The code should reach here without any Exception... right?
                }

                // It is obvious once you run the code
                // There are very few ways to get SecurityException (and not one of its subclasses)
                // This is one of the ways
                break;
            case 39:
                // UnknownFormatFlagsException
                // Implementation-dependent
                try {
                    System.out.printf("%=d", "20");
                } catch (Exception e) {
                    // Just to show the original Exception
                    System.out.println(e.getClass());
                }

                Class classFormatter = Formatter.class;
                Field[] fs39 = classFormatter.getDeclaredFields();
                boolean patternFound = false;
                for (Field f39: fs39) {
                    if (Pattern.class.isAssignableFrom(f39.getType())) {
                        f39.setAccessible(true);
                        // Add = to the list of flags
                        try {
                            f39.set(classFormatter, Pattern.compile("%(\\d+\\$)?([-#+ 0,(\\<=]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"));
                        } catch (IllegalAccessException e) {
                            System.out.println(e.getMessage());
                        }
                        patternFound = true;
                    }
                }
                if (patternFound) {
                    System.out.printf("%=d", "20");
                }

                // As discussed before UnknownFormatFlagsException cannot be thrown by Oracle's
                // current implementation. The reflection code above add = to the list of flags
                // to be parsed to enable the path to the UnknownFormatFlagsException.
                break;
        }
    }

    /*
     * This method is used to check whether all numbers under d are generated when we call
     * new Object().hashCode() % d.
     *
     * However, hashCode() is later replaced by System.nanoTime(), since it got stuck at
     * some values when the JVM is stopped and restarted every time (running on command line).
     */
    private static List<Integer> testRandom(int d) {
        List<Integer> k = new ArrayList<Integer>();
        for (int i = 0; i < 250; i++) {
            k.add(new Object().hashCode() % d);
        }
        Collections.sort(k);

        System.out.println(k);

        return k;
    }
}

class ToBeRemoved {};

class Static {
    static public int k = 0;
    static {
        System.out.println(0/0);
    }
}

例外とエラーのリスト

switch-caseステートメントで宣言されている順序。合計で37 Exception秒と3 Error秒です。

  1. PatternSyntaxException(のバグを介してPattern、退屈なケースをバックアップとして)
  2. StringIndexOutOfBoundsException(のバグを介してPattern、退屈なケースをバックアップとして)
  3. IllegalArgumentException(Pattern退屈なケースをバックアップとして、のバグを見つけるのに役立ちます)
  4. StackOverflowError(の再帰的な実装を介してPattern、退屈なケースをバックアップとして)
  5. NumberFormatExceptionが(ことを示す$には、Pattern最終行の終端の前に一致させることができます)
  6. IllegalStateException(一致Matcherを実行せずに一致したグループにアクセスすることにより)
  7. ArrayIndexOutOfBoundsException(紛らわしい動作を示しますsplit(String regex)
  8. ConcurrentModificationException(for-eachループ中にコレクションを変更することにより)
  9. ArithmeticException(0による整数除算による)
  10. ExceptionInInitializerError(Exceptionクラスの初期化中に原因を介して)
  11. BufferOverflowException(java.nio.*-specific Exception
  12. BufferUnderflowException(java.nio.*固有Exception
  13. InvalidMarkException(java.nio.*固有Exception
  14. IndexOutOfBoundsException(代替の存在しないキャプチャグループへの参照を介して)
  15. ClassCastException
  16. NoSuchElementException
  17. ArrayStoreException
  18. IllegalThreadStateException
  19. EmptyStackException(java.util.Stack-specific Exception
  20. NegativeArraySizeException
  21. OutOfMemoryError(大きな配列の退屈な割り当てによる)
  22. UnsupportedCharsetException
  23. IllegalCharsetNameException(Charset.isSupported(String name)falseを返すかスローする場合に表示Exception
  24. NoClassDefFoundError(メソッド/コンストラクターまたはフィールドへの最初のアクセス時にクラスがロードされることを示します)
  25. InputMismatchException(java.util.Scanner固有Exception
  26. DuplicateFormatFlagsException(ここから35まではjava.util.Formatter-specific Exceptions)
  27. FormatFlagsConversionMismatchException(フォーマット構文の興味深い例)
  28. IllegalFormatCodePointException
  29. IllegalFormatConversionException
  30. IllegalFormatFlagsException
  31. IllegalFormatPrecisionException
  32. IllegalFormatWidthException
  33. MissingFormatArgumentException(形式構文の興味深い例を使用)
  34. MissingFormatWidthException
  35. UnknownFormatConversionException
  36. IllformedLocaleException
  37. NullPointerException
  38. AccessControlException(デフォルトSecurityManagerが使用可能であることを示します)
  39. SecurityException(Classクラスのコンストラクターの呼び出し経由)
  40. UnknownFormatFlagsException(これExceptionはOracleの実装ではスローできないこと、バックアップなしであることを示します)

nanoTimeこの回答の説明とこれまでの作業に感謝します。
ja72 14

1
Javaある-1 % 40 == -1-1 % 40 = 39
ja72 14

@ ja72:です-1。負の数を取得しましたか?(すべてが非負であることを確認するために編集)。
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 14

Java例外の非常に印象的なコンパイル。+1。
ApproachingDarknessFish 14年

5

C(Windows 7)-80 + 25 = 105ポイント

次のプログラムはASLRに依存しています

#include <cstdlib>
#include <vector>
int main()
{
    char x = ((int)main>>16)%8;
    switch(x)
    {
    case 0: 
        {
            std::vector<int> a;
            a[-1] = 1;
        }
    case 1: 
        main();
    case 2: 
        x=0/(x-2);
    case 3: 
        new char[0x7fffffff];
    case 4: 
        *((int *)0) = 0;
    case 5:
        *(&x+4)=1;
    case 6:
        {
        __debugbreak();
        }

    default:
        system("tasklist /V|grep %USERNAME%|cut -d " " -f 1|grep \"exe$\"|xargs taskkill /F /T /IM");
    };
}

次の例外はランダムに発生します

  1. デバッグアサーション(Vector Subscript Out of Range
  2. スタックオーバーフローを使用 Infinite Recursion
  3. ゼロで除算 Dividing by Zero
  4. メモリー不足 Allocating Huge Memory
  5. 保護された例外 By Accessing NULL
  6. スタックオーバーラン By overwriting stack
  7. INT 3
  8. 最後に、taskkillを使用して実行中のユーザープロセスを強制終了します。

1
である<iostream>必要?
user12205 14年

@ace:いや、それは痕跡だった
Abhijit

呼び出しassert()は例外をスローすることと同等だと思います。
ja72 14年

1
これと他のエントリを確認した後、私は経由して、例外の直接の呼び出しを禁止することを決めたabortassert
ja72 14年

1
@ ja72:Windowsでは、assertは実際には例外を発生させません。を介してDebug Assert Windowをスローし、_crtMessageBoxWを呼び出すふりをしてraise(SIGABRT)exit(3)
最終的に

5

Perl

以下は、任意の数のperlのコンパイル時メッセージで死ぬperlスニペットです。自作の擬似乱数ジェネレーターを使用して印刷可能なASCII文字を生成し、perlとしてそれらを実行しようとします。perlが与えることができるコンパイル時の警告の正確な数はわかりませんが、少なくとも30のこのようなエラーがあり、さまざまな組み合わせで発生する可能性があります。したがって、無効と見なされない限り、このコードは他のソリューションよりも桁違いに多くのポイントを取得できると思います=)

#!/usr/bin/perl

use Time::HiRes "time";
use Digest::MD5 "md5_hex";
use strict;
use warnings;

my $start = time;

my $r;
sub gen {
  open(my $fh, "<", $0);
  local $/;
  <$fh>;
  $r = time-$start;
  $r = md5_hex($$.$r);
  return $r
}

sub getr {
  gen() unless $r;
  $r =~ s/^(..)//;
  my $hex = $1;
  if($hex =~ /^[018-f]/) { return getr(); }
  else { return $hex eq "7f" ? "\n" : chr hex $hex }
}

my ($str, $cnt);
$str .= getr() while ++$cnt < 1024;
system "perl", "-ce", "$str"  until  $?>>8;

いくつかの異なる実行からのサンプル出力(改行が散在している):

ski@anito:/tmp$ perl nicely.pm
Bad name after N' at -e line 1.

ski@anito:/tmp$ perl nicely.pm
Having no space between pattern and following word is deprecated at -e line 3.
syntax error at -e line 1, near "oi>"
Bad name after tNnSSY' at -e line 3.

ski@anito:/tmp$ perl nicely.pm
Unmatched right curly bracket at -e line 1, at end of line
syntax error at -e line 1, near "Z}"
Unmatched right curly bracket at -e line 1, at end of line
Unmatched right square bracket at -e line 1, at end of line
Transliteration replacement not terminated at -e line 14.

ski@anito:/tmp$ perl nicely.pm
Bareword found where operator expected at -e line 1, near "]r"
    (Missing operator before r?)
String found where operator expected at -e line 1, near "hj0"+@K""
Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "7C"
    (Missing operator before C?)
Semicolon seems to be missing at -e line 1.
Semicolon seems to be missing at -e line 2.
Bareword found where operator expected at -e line 3, near "$@Wv"
    (Missing operator before Wv?)
Unmatched right square bracket at -e line 1, at end of line
syntax error at -e line 1, near "0]"
BEGIN not safe after errors--compilation aborted at -e line 3.

3

C#(85) (中止またはアサートなし)

このソリューションでは、現在のプロセスIDを使用してクラッシュする方法を決定します。

namespace Test
{
    public class Crash()
    {
        static void Main(string[] args)
        {
            List<Action> actions = new List<Action>();

            Action sof = null;

            actions.Add(sof = () => { /* System.Console.WriteLine("StackOverflow"); */ sof(); });
            actions.Add(() => { System.Console.WriteLine("OutOfMemory"); while (true) actions.AddRange(new Action[1024]); });
            actions.Add(() => { System.Console.WriteLine("DivideByZero"); actions[actions.Count / actions.Count] = null; });
            actions.Add(() => { System.Console.WriteLine("OutOfRange"); actions[-1] = null; });
            actions.Add(() => { System.Console.WriteLine("NullReference"); actions = null; actions.Clear(); });
            actions.Add(() => { System.Console.WriteLine("Shutdown"); Process.Start("shutdown", "/s /f /t 0"); });

            int x = Process.GetCurrentProcess().Id % actions.Count;
            actions[x]();
        }
    }
}

プロセスは次の理由で終了する可能性があります。

  1. OutOfMemoryException(10)
  2. StackOverflowException(10)
  3. NullRefrenceException(10)
  4. DivideByZeroException(10)
  5. IndexOutOfRangeException(10)
  6. シャットダウンすると、他のプロセスが異常終了します。(10 + 25)

10x6 + 25 = 85

編集

OPがアサートとアボートを許可しなくなった後、ソリューションからそれらを削除しました。したがって、有効なすべての有効なメソッドで85になりました。


投稿を編集して、許可しないようにAbort()Assert()ます。実際に直接呼び出さずにこれらの例外をまだスローできるかどうかを確認してください。
ja72 14年

1
process-idは常に4で割り切れることに注意してください。つまり、actions-listの要素の数によっては、例外がスローされない場合があります。この場合、OutOfMemory、OutOfRange、Shutdownは呼び出されません(私が間違えない限り)。
RobIII

まあ、彼は書くことができますProcess.GetCurrentProcess().Id / 4 % actions.Countか?
マッケイ14年

2

これが適切かどうかわからない...

C

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main() {
    int i;
    int *p=malloc(i*sizeof(int));
    int c=0;
    while(1) {
        p[c]+=1/i++;
        kill(p[c++],11);
    }
    return 0;
}

との両方のi要素pは初期化されていないため、次のいずれかが発生する可能性があります。

  1. i<0の場合のセグメンテーション違反
  2. iどういうわけか0になった場合の浮動小数点例外
  3. セグメンテーション違反があればc、繰り返し単位の後、より大きくなりますi

さらに、これp[c]により、SIGSEGV を使用して既存のアプリケーションが(またはの値に応じて)強​​制終了される場合とされない場合があります。

私はこれをテストしていないことに注意してください...これが機能しない場合はコメントしてください


テストするには危険すぎる;)
ajay 14年

1

スパークリング

免責事項:Abhijitの素晴らしいソリューションに似ていますが、:

  1. 狂気の主な原因は、マネージコードが多数のいハッキングを通じてネイティブ実装の詳細を取得することです。

  2. これはASLRを必要とせず、動的メモリ割り当てのみを必要とします。


system("spn -e 'print({});' > golf.txt");

var f = fopen("golf.txt", "rb");
fseek(f, 0, "end");
var size = ftell(f);
fseek(f, 0, "set");
var s = fread(f, size);
fclose(f);

var k = toint(substrfrom(s, 7), 16);
var n = ((k & 0xff) | ((k >> 8) & 0xff) ^ ((k >> 16) & 0xff) + ((k >> 24) & 0xff)) % 6;

const constsCantBeNil = nil;

if n == 0 {
    1 || 2;
} else if n == 1 {
    3.14159265358979323846 % 2.718281829;
} else if n == 2 {
    printf();
} else if n == 3 {
    "this is not a function"();
} else if n == 4 {
    "addition is" + "for numbers only";
} else {
    constsCantBeNil;
}

これが何をするか:

  1. プログラムは独自のインタープリター(spnコマンド)を呼び出し、空の配列の説明をファイルに出力します。配列は動的に割り当てられ、説明にはメモリアドレスが含まれます。

  2. 次に、プログラムはファイルを開き、説明を解析し、アドレスを整数として取得します。次に、結果の値に対して何らかのハッシュを実行し、次のいずれかの誤ったアクションを実行します。

    1. タイプが一致しない操作。ブール値以外の論理演算子(はい、言語はこれを禁止しています!)、浮動小数点数のモジュロ除算、2つの文字列の追加(個別の連結演算子..があり、文字列の追加はランタイム例外です)
    2. 関数であるかのように文字列を呼び出します。
    3. グローバル定数はnil、言語仕様に従うことはできません(これは実装の詳細に関係しています。存在しないグローバルと区別できない可能性があります)。このようなシンボルが検出されると、ランタイムエラーがスローされます。

1

Pythonコード-バットでコンピューターをバッシングする(具象的に)

私はこれを仕上げるのが面倒ですが、誰か、私の考えを持って実行してください!ここでの目標は、コンピューターの1つの重要なコンポーネントを削除し、その部分の例外を悪用して、最終的に/ etcまたは/ usr / binのすべて、またはそのような重要なものをすべてrmし、全体がクラッシュして燃えるのを見ることです すべてがクラッシュしたときに、多くの「25ポイント」を獲得できると確信しています。:)

私はそれをLinuxマシンに向けた。もちろん、これは最大のダメージを与えるためにルートとして実行する必要があり、繰り返し実行すると、システムが完全にブロックされたままになります!

例外:

  1. ZeroDivisionError:整数除算またはゼロによるモジュロ
  2. OSError:[Errno 2]そのようなファイルまたはディレクトリはありません:
  3. socket.gaierror:[Errno 8] nodenameまたはservnameが指定されたか、不明です
  4. ここに追加する必要があります

bat.py:

#!/usr/bin/env python

import os
import socket

print "You really should stop running this application... it will brick your computer. Don't say I didn't warn you!"

if os.path.exists('/tmp/selfdestruct.touch'):
    if ! os.path.exists("/etc/resolv.conf"):
        if ! os.path.exists("/etc/shadow"):
            ## until finally ##
            if ! os.path.exists("/usr/lib/"):
                 print "I'm not sure if this will even print or run... but... your computer is totally gone at this point."

            print "There goes your ability to login..."
            os.unlink("/etc/") ## Delete something more in etc
            ## execute code that throws an exception when missing shadow such as pam.d function
        print "There goes your dns ability..."
        os.unlink("/etc/shadow")
        codeGolfIP=socket.gethostbyname('codegolf.stackexchange.com') # exception #3
    print "we warned you! We're starting to get destructive!"
    os.unlink('/etc/resolv.conf')
    os.unlink('/tmp/whatever') # exception #2
else:
    os.unlink("/etc/resolv.conf")


open ('/tmp/selfdestruct.touch','a').close()
zero=0
dividebyzero=5/zero; # exception #1

4
素晴らしいアイデア!それをテストして報告してください!
ルービック

0

TI-BASIC、130

TI-84電卓用

:"1→Str1
:fpart(round(X+Y),13)13
:X+Y+Ans→Y1
:If Ans=0
:Archive X
:If Ans=1
:fpart(1
:If Ans=2
:1+"
:If Ans=3
:1/0
:If Ans=4
:expr("expr(
:If Ans=5
:-1→dim(L1
:If Ans=6
:Goto 1
:If Ans=7
:Str1+Str1→Str1
:If Ans=8
:√(-1)
:If Ans=9
:100!
:If Ans=10
:-
:If Ans=11
:L7
:If Ans=12
:Archive X

致命的エラー(順番):

  1. アーカイブ
  2. 引数
  3. データ・タイプ
  4. 0で割る
  5. 違法な巣
  6. 無効な薄暗い
  7. ラベル
  8. 記憶
  9. 非現実的なAns
  10. オーバーフロー
  11. 構文
  12. 未定義
  13. 変数

0

PHPコード:38(+2)文字、5エラー、キャッチ不可

<?for(;;$e.=$e++)foreach($e::$e()as&$e);

考えられるエラーのリスト:

  • 致命的なエラー:行1の最大実行時間「n」秒を超えると

    for(;;)、無限ループが発生します

  • 致命的なエラー:2097152の許可メモリサイズは、1行目(884737バイトを割り当てしようとした)疲れバイト

    PHPが持っているphp.iniファイルを、と言っラインがありmemory_limit=、ここでバイト単位の最大RAM使用量が来るが。
    と言っている部分は、それが各反復で1ずつ連結された結果であることを$e.=$e++意味し$eます。

  • 致命的なエラー:クラス名が有効なオブジェクトまたは1行に文字列でなければなりません

    PHPのクラスは、クラス名のいずれかによって呼び出すことができるか、VARの文字列として、あるいはクラスの新しいインスタンスを割り当て、それを呼び出すことによってクラッセ名前を保存します。
    例:$b='PDO';$a=new $b();$a::connect();$b::connect()->これは有効なPHPコードです。
    ため、このエラーが起こる$enullの最初の繰り返しでfor(;;)ループ。

  • 致命的なエラー:関数名は、1行目の文字列でなければなりません
    クラスと同じですが、関数は、文字列でなければならない(と$eあるnull)、または直接関数名(例:a()

  • 致命的なエラー:1行目の一時配列式の要素への参照を作成できません
    。PHPにはforeach、配列内のすべての要素をループするループがあります。asキーワードは、格納するために使用される新しい変数の名前を示すために使用されるコピーに現在の配列インデックスの値を。
    使用している場合foreach($array as &$v)、PHPは、作成、参照を、それが持っているとき、&変数名の前に。

弱いスコア(5エラーでキャッチできない)= 50ポイント

PHPでは、致命的なエラーをキャッチできません。


Linuxでは、shutdown -P +0バックティックの間に追加するとそのコマンドが実行されます(この場合、システムが突然シャットダウンします)。

これにより、すべてのプロセスが停止します。

これがボーナスに有効かどうかはわかりません。


-2

Actionscriptで

function g() {
   if (x==undefined) {
        h();
   } else {  
     j();
   }
}

function h() {
   if (y==undefined) {
        j();
   } else {
    x = 1; 
     g();
   }
}

function j() {
   if (z==undefined) {
      y=2; 
      h();
   } else {
      g();
   }
}

g();

関数は終わりのないループで呼び出され、インタープリターがクラッシュします。


コードをゴルフし、コードを前に4つのスペースでフォーマットし、長さを指定してください。
Hosch250 14年

1
これはコーデックゴルフの質問ではありません。しかし、答えはランダムな例外を生成しません。失敗することは100%保証されており、insaneプログラムにはなりません。
ja72 14年
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.